在 linux 中,如何在 2 个线程之间进行同步(在 linux 上使用 pthreads)? 我想,在某些情况下,一个线程会阻塞自己,然后由另一个线程恢复。在Java中,有wait()、notify()函数。我在 pthreads 上寻找相同的东西:
这个我看过,不过只有mutex,有点像Java的synchronized关键字。那不是我要找的。 https://computing.llnl.gov/tutorials/pthreads/#Mutexes
谢谢。
最佳答案
您需要一个互斥量、一个条件变量和一个辅助变量。
在线程 1 中:
pthread_mutex_lock(&mtx);
// We wait for helper to change (which is the true indication we are
// ready) and use a condition variable so we can do this efficiently.
while (helper == 0)
{
pthread_cond_wait(&cv, &mtx);
}
pthread_mutex_unlock(&mtx);
在线程 2 中:
pthread_mutex_lock(&mtx);
helper = 1;
pthread_cond_signal(&cv);
pthread_mutex_unlock(&mtx);
你需要辅助变量的原因是因为条件变量会受到 spurious wakeup 的影响。 .它是辅助变量和条件变量的组合,可为您提供准确的语义和高效的等待。
关于linux - linux pthreads中2个线程之间的同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2136169/