Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can 2 pthread condition variables share the same mutex?

Tags:

I went through the documentation in http://www.opengroup.org/onlinepubs/009695399/functions/pthread_cond_wait.html but this is not mentioned explicitly. Any prompt response will be very appreciated.

like image 657
Fanatic23 Avatar asked Oct 31 '10 06:10

Fanatic23


2 Answers

Yes. This is sometimes a good idea if you have separate conditions you'd like to wait on. For instance, you might have a queue and condition variables for both "not full" and "not empty" etc... Someone putting data on the queue waits for "not full". Someone taking data off the queue waits for "not empty". They all use the same mutex.

like image 44
xscott Avatar answered Sep 19 '22 16:09

xscott


Yes. This is common pratice:

Typical example:

mutex queue_mutex;  cond queue_is_not_full_cond; cond queue_is_not_empty_cond;  push()     lock(queue_mutex)       while(queue is full)         wait(queue_is_not_full_cond,queue_mutex);       do push...       signal(queue_is_not_empty_cond)    unlock(queue_mutex)  pop()     lock(queue_mutex)       while(queue is empty)         wait(queue_is_not_empty_cond,queue_mutex);       do pop...       signal(queue_is_not_full_cond)    unlock(queue_mutex) 
like image 139
Artyom Avatar answered Sep 20 '22 16:09

Artyom