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

标签 linux pthreads

在 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/

相关文章:

linux - Python 3 导入错误_Py_set_inheritable_async_safe

c - 如何使用 pthread、pthread_exit 将 * 转换为 double/float

c - 即使 SA_RESTART 标志设置为零,阻塞函数 accept() 在 SIGINT 发生时重新启动

c - 使用全局变量同步 p_threads

c - 递归函数和pthreads

python - Linux 上使用 pygtk (gtk.gdk) 的桌面/根窗口上的键盘/鼠标事件

html - 如何将 css 背景 url 转换为嵌入 html url?

c - 如何让所有人都可以使用我的 API?

linux - 执行sed命令时出错

c++ - 为什么 cout 不适用于 pthreads?