I want synchronize two threads if an event happen, i found that many ressources suggest the use of pthread_cond
in such situations however i don't see the difference between the use of pthread_cond
and mutexes
:
We can use the following code :
// thread 1 waiting on a condition
while (!exit)
{
pthread_mutex_lock(&mutex); //mutex lock
if(condition)
exit = true;
pthread_mutex_unlock(&mutex);
}
... reset condition and exit
// thread 2 set condition if an event occurs
pthread_mutex_lock(&mutex); //mutex lock
condition = true;
pthread_mutex_unlock(&mutex);
Instead of :
//thread 1: waiting on a condition
pthread_mutex_lock(&mutex);
while (!condition)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
//thread 2: signal the event
pthread_mutex_lock(&mutex);
condition = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
Could you please help me undrestand the best practices / situations in which we have to use pthread_cond