c++ - pthread_cond_wait 和 pthread_mutex_unlock 是否冲突?

标签 c++ multithreading pthreads

我在 Linux 中使用 pthread 实现手动重置事件,这类似于 Windows 中的 WaitForSingleEvent。我找到了这篇文章

pthread-like windows manual-reset event

然后跟着它,但是有一点让我感到困惑:

void mrevent_wait(struct mrevent *ev) {
     pthread_mutex_lock(&ev->mutex);
     while (!ev->triggered)
         pthread_cond_wait(&ev->cond, &ev->mutex);
     pthread_mutex_unlock(&ev->mutex);
}
  • pthread_cond_wait: 以原子方式释放互斥量并导致调用线程阻塞在条件变量 cond 上;
  • pthread_mutex_unlock: 尝试解锁指定的互斥量。如果互斥量类型是 PTHREAD_MUTEX_NORMAL,则不提供错误检测。如果线程试图解锁一个未锁定的互斥锁或一个已解锁的互斥锁,则会导致未定义的行为。

我害怕的是当 pthread_cond_wait 释放互斥锁时,然后 pthread_mutex_unlock 可能会出现未定义的行为(这种事情会让我发疯,他们怎么不处理它:-D)

谢谢。

最佳答案

The standard说:

Upon successful return, the mutex has been locked and is owned by the calling thread.

这意味着当返回时,pthread_cond_wait 自动 锁定关联的互斥体。

工作流程是这样的:

  • 你锁定了一个互斥体
    • pthread_cond_wait 原子地阻塞和解锁互斥锁(这样其他线程可能会到达这里)
    • 当条件到达时,pthread_cond_wait 自动返回并锁定互斥体
  • 你解锁了互斥体

I don't think pthread_cond_wait blocks and unlocks

那是因为你没有阅读我提供的链接。

These functions atomically release mutex and cause the calling thread to block on the condition variable cond;

关于c++ - pthread_cond_wait 和 pthread_mutex_unlock 是否冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6532767/

相关文章:

java线程与java进程性能下降

C++,如何用另一个类的线程更改另一个类的变量

c++ - 一个人如何降低 std::shared_ptr?

c++ - std is_member_function_pointer 中的模板类型

c# - 在压缩一个巨大的文件夹时,如何为其他应用程序提供一些磁盘时间? C#

c# - 性能调整分隔文件读取和写入数据库

c++ - 铿锵错误 : note: candidate constructor (the implicit move constructor) not viable:

c++ - 使用递增值初始化全局变量

gcc - gcc的-lpthread选项

c++ - 如何用pthread获取信号量的信息