0

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

Mouin
  • 1,025
  • 4
  • 19
  • 33
  • Regarding your second example, 1. You don't need to latch the mutex to signal the cond-var (though you certainly *can*). 2. You **do** need to latch the mutex before *using* (read or write) the predicate data (in your case, `condition`). Your second code never sets `condition`, so though a signal will happen, the while-loop never breaks (assuming it is initially false). Intending only to be helpful and not self-gratifying, [maybe this will help understand better](https://stackoverflow.com/questions/14924469/does-pthread-cond-waitcond-t-mutex-unlock-and-then-lock-the-mutex/14925150#14925150). – WhozCraig Jan 13 '17 at 10:33

1 Answers1

0

Your first example will spin and use CPU all the time, while waiting on a condition variable will suspend the process and it won't run until the condition variable is signalled. If you just have one CPU in the machine in the first example thread 1 could also end up blocking thread 2 from running for a long time so it won't even have a chance to signal the condition.

Spinning is a waste of CPU time, waste of electricity and could end up being many magnitudes slower.

(you do have a bug in your second example, but I'm pretty sure that's just a mistake when making up examples, this is why it's good practice to actually have runnable and tested examples in questions)

Art
  • 19,807
  • 1
  • 34
  • 60