Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ pthread_cond_wait和pthread_mutex_unlock是否冲突?_C++_Multithreading_Pthreads - Fatal编程技术网

C++ pthread_cond_wait和pthread_mutex_unlock是否冲突?

C++ pthread_cond_wait和pthread_mutex_unlock是否冲突?,c++,multithreading,pthreads,C++,Multithreading,Pthreads,我在Linux中使用pthread实现手动重置事件,这类似于Windows中的WaitForSingleEvent。我找到了这个帖子 但是有一件事让我困惑: void mrevent_wait(struct mrevent *ev) { pthread_mutex_lock(&ev->mutex); while (!ev->triggered) pthread_cond_wait(&ev->cond, &ev-&g

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

但是有一件事让我困惑:

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\u cond\u wait释放互斥锁时,那么pthread\u mutex\u unlock可能会出现未定义的行为(这种事情会让我发疯,他们为什么不处理它:-D)

谢谢。

说:

成功返回后,互斥锁将 已被锁定,并归 调用线程

这意味着当返回时,
pthread\u cond\u wait
会自动锁定相关的互斥锁

工作流程如下所示:

  • 你锁定了一个互斥锁
    • pthread\u cond\u wait
      以原子方式阻塞和解锁互斥锁(因此其他线程可能会到达这里)
    • 当条件到达时,
      pthread\u cond\u wait
      自动返回并锁定互斥锁
  • 解锁互斥锁

我不认为pthread_cond_wait阻塞 解锁

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

这些函数以原子方式释放 互斥并使调用线程 在条件变量cond上阻塞


总之,在
pthread\u cond\u wait
之后解锁互斥锁是有效的(并且是必需的)。我认为pthread\u cond\u wait不会阻塞和解锁。但是如果它首先解锁互斥锁,然后尝试锁定互斥锁,我认为这可能会导致死锁。顺便说一句,有人知道为什么我们必须将pthread_cond_wait放入一个while循环吗?我可以只使用if语句吗?谢谢大家!@请看我编辑过的答案。第二个问题的答案如下: