Reputation: 3110
I am developing an application in C where in thread A have to wait for three events(like reception of data) from 3 different threads namely B, C, D. I am able to implement for a single event using pthread_cond_wait, pthread_cond_signal and mutex but I want to expand this concept to multiple events using single condition variable and single mutex. Can somebody please help me in resolving this issue.
Thanks in advance.
Upvotes: 2
Views: 3444
Reputation: 239341
There's really nothing tricky to it: presuming for one event you have code in thread A like:
pthread_mutex_lock(&lock);
while (!event_b_pending)
pthread_cond_wait(&cond, &lock);
/* Process Event B */
with code in thread B like:
pthread_mutex_lock(&lock);
event_b_pending = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
Then for three events, you would change thread A to:
pthread_mutex_lock(&lock);
while (!event_b_pending && !event_c_pending && !event_d_pending)
pthread_cond_wait(&cond, &lock);
if (event_b_pending)
{
/* Process Event B */
}
if (event_c_pending)
{
/* Process Event C */
}
if (event_d_pending)
{
/* Process Event D */
}
with threads C and D working like thread B (except setting the appropriate flag).
Upvotes: 5