向条件变量发出信号(pthreads)
假设某个条件变量“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?
EDIT: 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该始终在调用
pthread_cond_signal
后解锁互斥锁。以下是一些值得阅读的好问题/答案:在不锁定互斥体的情况下调用 pthread_cond_signal
我现在不会想到这一点,但我很确定有一个很好的理由(就竞争条件而言)您不想在发出信号之前解锁互斥体。
You should always unlock the mutex after calling
pthread_cond_signal
. Here are some good questions/answers to read:Calling pthread_cond_signal without locking mutex
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.
如果保持互斥锁锁定,则被唤醒的线程无法获取互斥锁,因此将阻塞在 pthread_cond_wait 等待重新获取互斥锁。
您无需保持互斥体锁定即可调用
pthread_cond_signal
。事实上,如果您的应用程序逻辑可以在互斥锁未锁定时使用信号,那么这是一个更好的方法——操作系统可以立即调度等待线程,而不必等待信号线程在继续之前解锁互斥体。但是,在这种情况下,必须注意确保唤醒不会丢失,并且不会出现“错误”线程被唤醒的问题。如果您使用直接的谓词,这在实践中应该不是问题。
If you keep the mutex locked, then the thread being woken cannot acquire the mutex, so will block in
pthread_cond_wait
waiting to reacquire the mutex.You do not need to hold the mutex locked to call
pthread_cond_signal
. In fact, if your application logic can work with a signal when the mutex is not locked then that is a better way to do it --- the OS can schedule the waiting thread immediately, and it doesn't have to wait for the signalling thread to unlock the mutex before proceeding.However, in this scenario care must be taken to ensure that the wake-up is not lost, and you don't have a problem with the "wrong" thread being woken. If you use a straight-forward predicate, this shouldn't be a problem in practice.