linux pthreads中2个线程之间的同步

问题描述:

在Linux中,如何在2个线程之间进行同步(在Linux上使用pthreads)? 我想在某些情况下,一个线程将自身阻塞,然后再由另一个线程恢复.在Java中,有wait(),notify()函数.我正在pthreads上寻找相同的东西:

In linux, how can synchronize between 2 thread (using pthreads on linux)? I would like, under some conditions, a thread will block itself and then later on, it will be resume by another thread. In Java, there is wait(), notify() functions. I am looking for something the same on pthreads:

我已经读过这篇文章,但是它只有互斥量,有点像Java的synced关键字.那不是我想要的. https://computing.llnl.gov/tutorials/pthreads/#Mutexes

I have read this, but it only has mutex, which is kind of like Java's synchronized keyword. That is not what I am looking for. https://computing.llnl.gov/tutorials/pthreads/#Mutexes

谢谢.

您需要互斥体,条件变量和帮助变量.

You need a mutex, a condition variable and a helper variable.

在线程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);

之所以需要辅助变量是因为条件变量可能会受到虚假唤醒的困扰.它是辅助变量和条件变量的组合,可为您提供确切的语义和有效的等待时间.

The reason you need a helper variable is because condition variables can suffer from spurious wakeup. It's the combination of a helper variable and a condition variable that gives you exact semantics and efficient waiting.