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

时间:2010-01-25 22:29:58

标签: linux pthreads

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

我已经读过这个,但它只有mutex,有点像Java的synchronized关键字。这不是我想要的。 https://computing.llnl.gov/tutorials/pthreads/#Mutexes

谢谢。

2 个答案:

答案 0 :(得分:10)

您需要互斥锁,条件变量和辅助变量。

线程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影响。它是辅助变量和条件变量的组合,为您提供精确的语义和有效的等待。

答案 1 :(得分:0)

您还可以查看自旋锁。尝试man / google pthread_spin_init,pthread_spin_lock作为起点

根据您的应用程序的具体情况,它们可能比互斥锁更合适