0

There are two thread.
No.1 is producer and No.2 is consumer
1 and 2 thread are using same buffer.

I want to know whether I need to set Mutex lock/unlock on No.1 thread.
Could you guide for this?

No.1

{

 /*[Need here Mutex lock? pthread_mutex_loc(&mut);]*/

 setting_buffer();

 pthread_cond_signal(&cond);

 /*[Need here Mutex unLock? pthread_mutex_unlock(&mut);]*/

}

No.2

{

 pthread_mutex_loc(&mut);

 pthread_cond_wait(&cond, &mut);


 consumming_buffer();


 pthread_mutex_unlock(&mut);

}
zzn
  • 2,376
  • 16
  • 30
  • yes, thread 1 need to lock before setting the buffer – zzn Apr 28 '19 at 03:57
  • Thank you for your answer, Could you let me know more detail? – jjumman Apr 28 '19 at 04:09
  • Note: You’ll have a deadlock since consumer locks, then waits, so the producer will never get the lock to set the buffer. If this were the code you wouldn’t need mutexes at all since the signal is used to tell when things are done. But if they are in a loop or can be called whenever then you do need locking, unless the containers are lock free, or handle locking themselves. – Sami Kuhmonen Apr 28 '19 at 04:23
  • @jjumman check this question: https://stackoverflow.com/questions/16522858/understanding-of-pthread-cond-wait-and-pthread-cond-signal – zzn Apr 28 '19 at 04:30

1 Answers1

0

Yes, you do need to lock the mutex somewhere in the signalling / buffer-setting side.

A condition variable must always be paired with some condition over shared state that the waiting thread is waiting for - that's why it's called a condition variable. The waiting side must always re-check the condition it is waiting for after pthread_cond_wait() returns - it is allowed to return early even if it hasn't been signalled yet. In almost all cases, this means that you should be calling pthread_cond_wait() in a loop that checks the condition:

pthread_mutex_lock(&mut);

while (!buffer_is_set())
    pthread_cond_wait(&cond, &mut);

consume_buffer();

pthread_mutex_unlock(&mut);

The buffer_is_set() condition is necessarily going to look at some shared state that the other thread is updating, so the other thread must also lock the mutex to prevent racing access to that state:

 pthread_lock(&mut);

 setting_buffer(); /* Now buffer_is_set() will return true */

 pthread_cond_signal(&cond);

 pthread_unlock(&mut);

Note that the mutex only needs to be locked around the setting_buffer() call - it's safe to call pthread_cond_signal() after unlocking the mutex.

caf
  • 233,326
  • 40
  • 323
  • 462