gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:36 25 4
gpt4 key购买 nike

这个问题是关于 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com