我正在考虑使用以下机制来同步两个/多个线程。我认为唯一的缺点是 CPU 使用率。请分享您对此机制的意见。这个实现有什么问题吗? (假设 gcc 的 _sync* 函数是可移植的)
//logic is that if lock = 1 means a thread has acquired the lock.
// lock = 0 means lock is free.
// acquireLock:
// add 1 to lock if value is 1 this thread gets the lock
// if value is > 1 mean some one else have taken the lock, so decrement the count
int lock = 0 ; // global variable.
void acquireLock()
{
while(__sync_add_and_fetch (&lock,1) > 1)
{
__sync_add_and_fetch (&lock,-1);
}
}
void releaseLock()
{
__sync_add_and_fetch (&lock,-1);
}
因此,任何想要访问共享数据或全局数据的线程都将首先调用 acquireLock,访问全局数据,然后再释放锁。
最佳答案
你正在实现一种自旋锁。您可以使用 CAS 循环代替递增和递减:
void acquireLock () {
while (!_sync_bool_compare_and_swap(&lock, 0, 1)) {}
}
void releaseLock () {
int unlock_success = _sync_bool_compare_and_swap(&lock, 1, 0);
assert(unlock_success);
}
比较和交换将检查变量内容是否与预期值(第二个参数)匹配。如果是,它会将变量设置为新值(第三个参数)。如果预期值不匹配,则调用失败。这是一个原子操作。
关于c++ - 无锁同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17355816/