Signalling a condition variable (pthreads)
Asked Answered
C

2

6

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.

Cooks answered 3/3, 2011 at 1:4 Comment(1)
+1 for answering your own question.Yangyangtze
Y
4

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.

Yangyangtze answered 3/3, 2011 at 1:44 Comment(3)
If after signalling the condition variable and unlocking the mutex, the thread immediately calls pthread_mutex_lock() on that mutex, is it guaranteed not to starve the threads previously awoken by pthread_cond_signal() ?Cooks
@ManRow: There may be such a guarantee in the Priority Scheduling option, if the right priorities are set. Otherwise, definitely not.Yangyangtze
The good reason is avoiding priority inversion: groups.google.com/group/comp.programming.threads/msg/… linked from #4544734Ingather
C
4

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.

Criminal answered 3/3, 2011 at 11:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.