I am trying to find out execution of mutual exclusion and conditional variable in case of multiple threads produce and single thread consume.
Here is the sample code :
#include<stdio.h>
#include<pthread.h>
int done = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
void *thr2(void *arg) {
pthread_t self;
self=pthread_self();
pthread_mutex_lock(&m);
done = 1;
pthread_cond_signal(&c);
pthread_mutex_unlock(&m);
return NULL;
}
void *thr1(void *arg) {
pthread_t self;
self=pthread_self();
pthread_mutex_lock(&m);
while (done == 0)
{
pthread_cond_wait(&c, &m);
}
pthread_mutex_unlock(&m);
}
int main(int argc, char *argv[]) {
pthread_t p,q,r;
pthread_create(&q, NULL, thr1, NULL);
sleep(2);
pthread_create(&p, NULL, thr2, NULL);
pthread_create(&r, NULL, thr2, NULL);
pthread_join(p,NULL);
pthread_join(q,NULL);
pthread_join(r,NULL);
return 0;
}
In this code, I am expecting thread1 to wait on conditional variable done. So, thread2 or thread3 when any one starts and gets mutex and chanegs done to 1. It has to signal thread1 which is waiting and thread1 will start execution.
But, I see that even though thread1 is waiting on conditional variable done=0 and after signal from thread2, another thread which i created for thread2 method gets mutex.
I would like to know if anything wrong in my expectation of output. I am trying to implement blocking queue with similar case where there can be more than one producer and single consumer.
Thanks, Poovannan.