没有锁的同步

ira*_*ppa 2 c c++ multithreading gcc

我正在考虑使用以下机制来同步两个/多个线程.我认为唯一的缺点是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);
}
Run Code Online (Sandbox Code Playgroud)

因此,任何想要访问共享或全局数据的线程都将首先调用acquireLock,访问全局数据然后释放Lock.

jxh*_*jxh 5

你正在实现一种自旋锁.您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)

比较和交换将检查变量内容是否与期望值(第二个参数)匹配.如果是,则将变量设置为新值(第三个参数).如果预期值不匹配,则调用失败.这是一个原子操作.