Does the pthread library (in C/C++) have a function like pthread_cond_wait(&cond, &mutex)
that can wait for conditional signals (such as pthread_cond_signal(&cond1)
, pthread_cond_signal(&cond2)
and so on...) from multiple different threads?
What you're describing is not about different threads -- pthread_cond_wait()
/ pthread_cond_signal()
already handle that just fine, as indeed they need to do to serve their intended purpose. If a given thread is waiting on condition variable cond1
then it can be awakened by any thread that signals or broadcasts to cond1
. And ultimately, that may be the direction you want to go.
But what you actually asked about is whether a thread can block on multiple condition variables at the same time, and no, pthreads makes no provision for that. Nor would that make sense for the usage model for which condition variables are designed.
I suspect that you are looking at CV waiting / signaling as purely a notification mechanism, but this is altogether the wrong view. A thread uses a condition variable to suspend execution until another thread performs work that causes some condition to be satisfied (otherwise, why wait at all)? That's normally a condition that can be evaluated based on data protected by the associated mutex, so that the prospective waiting thread can
- avoid data races involving the data in question (by locking the mutex at the beginning, before accessing them, and relying on other threads to do the same);
- be assured (because it holds the mutex locked) that the condition will not change unexpectedly after it is evaluated;
- avoid waiting at all when the condition is already satisfied;
- verify when it resumes from waiting that the condition in fact is satisfied (MANDATORY).
When the condition indeed is satisfied, the thread moves on with whatever action it wanted to perform that required the condition to be satisfied. That's important. The thread waited to be able to perform a specific thing, so what does it matter if the conditions are then right for performing some other thing, too? And if it wants to perform that other thing next, then it can do it without waiting if the conditions for that still hold.
On the side of the signal sender, you should not think about it as notifying a specific thread. Instead, it is announcing to any thread that cares that something it is presently interested in may have changed.
I appreciate that this is all fairly abstract. Multithreaded programming is challenging. But this is why students are given exercises such as producer / consumer problems or the Dining Philosophers problem. Learn and apply the correct idioms for CV usage. Think about what they are achieving for you. It will become clearer in time.