我正在考虑使用以下机制来同步两个/多个线程。我认为唯一的缺点是 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,访问全局数据,然后再releaseLock。