问题描述
假设某些条件变量"cond"与互斥量变量"mutex"相关联.如果某个线程在调用pthread_cond_wait(&cond,&mutex)
之后在cond
上休眠,并且另一个已锁定mutex
的线程已经完成,那么该线程是在调用pthread_mutex_unlock(&mutex)
之前还是之后调用pthread_cond_signal(&cond)
无关紧要?如果它调用pthread_cond_signal(&cond)
,它是否甚至需要完全解锁互斥锁,因为睡眠线程仍然会获取该互斥锁?
Suppose some condition variable "cond" is associated with a mutex variable "mutex". If a thread is sleeping on cond
after calling pthread_cond_wait(&cond,&mutex)
, and another thread that has mutex
locked is finished, does it matter whether that thread calls pthread_cond_signal(&cond)
before or after calling pthread_mutex_unlock(&mutex)
? Does it even need to unlock the mutex at all if it calls pthread_cond_signal(&cond)
, since the sleeping thread will acquire the mutex anyway?
根据 https://computing.llnl.gov/tutorials/pthreads/# ConVarOverview ,在调用pthread_cond_signal()之后未能解锁互斥锁可能无法完成匹配的pthread_cond_wait()例程(它将被阻止)."我猜想那是需要解锁的,也许只有之后才需要.
According to https://computing.llnl.gov/tutorials/pthreads/#ConVarOverview, "Failing to unlock the mutex after calling pthread_cond_signal() may not allow a matching pthread_cond_wait() routine to complete (it will remain blocked)." I guess then, unlocking, and perhaps only afterwards, is required.
推荐答案
在调用pthread_cond_signal
之后,应始终解锁互斥锁.这里有一些很好的问题/答案,可供阅读:
You should always unlock the mutex after calling pthread_cond_signal
. Here are some good questions/answers to read:
在不锁定互斥体的情况下调用pthread_cond_signal
现在不会出现在我身上,但是我很确定有充分的理由(就比赛条件而言)您不想在发信号之前解锁互斥体.
It won't come to me right now, but I'm pretty sure there's a good reason (in terms of race conditions) that you don't want to unlock the mutex before signalling.
这篇关于发出条件变量的信号(pthreads)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!