c++ - pthread_cond_wait() 能否始终赢得锁定互斥体的竞争?

标签 c++ c multithreading pthreads

这个问题是关于 llnl 中的 pthread 教程的. 假设有三个线程。

线程 1:

pthread_mutex_lock(&mutex)
do_something...
if condition
    pthread_cond_signal(&con)
pthread_mutex_unlock(&mutex)
repeat

线程 2:

pthread_mutex_lock(&mutex)
do_something...
if condition
    pthread_cond_signal(&con)
pthread_mutex_unlock(&mutex)
repeat

线程 3:

pthread_mutex_lock(&mutex)
while(condition not holds)
    pthread_cond_wait(&con)
    do_something...
pthread_mutex_unlock(&mutex)

假设 Thread1 检查条件是否满足,然后发送信号唤醒 Thread3。最后它解锁互斥体。但与此同时,线程 2 正试图锁定互斥锁。

我的问题是:是否可以保证 Thread3 始终在竞争中获胜?

如果不是那么在Thread2 do_something...之后,条件变量可能会改变,然后当Thread3 锁定互斥量时,条件变量与什么不同它期望。

最佳答案

我的问题是:是否可以保证 Tread3 在比赛中始终获胜?

没有这样的保证。来自 POSIX :

The pthread_cond_signal() function shall unblock at least one of the threads that are blocked on the specified condition variable cond (if any threads are blocked on cond).

If more than one thread is blocked on a condition variable, the scheduling policy shall determine the order in which threads are unblocked. When each thread unblocked as a result of a pthread_cond_broadcast() or pthread_cond_signal() returns from its call to pthread_cond_wait() or pthread_cond_timedwait(), the thread shall own the mutex with which it called pthread_cond_wait() or pthread_cond_timedwait(). The thread(s) that are unblocked shall contend for the mutex according to the scheduling policy (if applicable), and as if each had called pthread_mutex_lock().

(强调我的)。

如果不是,那么在 Tread2 do_something... 之后,条件变量可能会发生变化,然后当 Tread3 锁定互斥量时,条件变量与预期的不同。

如果线程的执行顺序很重要,那么您可能需要重写代码。

关于c++ - pthread_cond_wait() 能否始终赢得锁定互斥体的竞争?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38304512/

相关文章:

C++ 未修改的 bool 数组更改 (OS X)

c++ 将枚举值标记为已弃用?

c - Typedef 函数指针,用于返回指向其自身类型函数的指针的函数?

c - GTK3 调整大小尝试使窗口呈指数增长

java - 程序在多线程中无法顺利结束

c++ - 我如何获得顺序线程ID

c++ - add_lvalue_reference 有什么作用?

c++ - 使用 libusb-win32 与 USB 转 DMX512 接口(interface)通信,找不到任何端点

java - UI 线程与其他线程之间的通信使用处理程序

c# - 在 visual studio c++ 中绘制实时图形