Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signalling a condition variable (pthreads)

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.

like image 463
ManRow Avatar asked Mar 03 '11 01:03

ManRow


1 Answers

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.

like image 162
R.. GitHub STOP HELPING ICE Avatar answered Sep 27 '22 19:09

R.. GitHub STOP HELPING ICE