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

相关文章:

C++ 使用 std::sscanf 和 std::string

c++ - 堆分配问题

android - “pm install”命令在Android上无效

c - 通过随机生成的索引进行分配

C中调用main函数

c++ - 强制评估 constexpr 静态成员

c - 我不能将指针声明为全局变量

java - 在 Java 中上传目录时出现 Amazon S3 SdkClientException

c# - 暂停线程

multithreading - 异步 F# 与 CCR 框架