25

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.

2 Answers 2

37

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

Why should it signal when there is no wait by other thread?
27

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.

3 Comments

Thanks a lot. Any relevant links?
Very late comment, but using 2 condvars with one mutex is actually recommended practice in e.g. the queue case, see Butenhof 'Programming with Posix Threads.'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.