multithreading - Explanation why conditional variable in C does not work correctly -


i want write simple multithreaded program making use of conditional variables in c.

i want have main thread (thread a) sleeps 5 sec , wake waiting clients (therads b, possible many) print message. should repeated time.

i have read manual don't understand why not work. let's assume have variables given threads via pointers (properly, have checked that):

pthread_mutex_t* mutex; pthread_cond_t* cond; int* variable; 

i have following code:

thread (sleeping):

while(1) {     lockmutex(mutex);     (*variable) = 1;     pthread_cond_broadcast(cond);     unlockmutex(mutex);     sleep(5);     lockmutex(mutex);     (*variable) = 0;     pthread_cond_broadcast(cond);     unlockmutex(mutex); } 

thread b (printing):

while(1) {     lockmutex(mutex);     while((*variable) == 1)         pthread_cond_wait(cond, mutex);     unlockmutex(mutex);     fprintf("active thread! number: %d\n", id);     lockmutex(mutex);     while((*(variable))==0)         pthread_cond_wait(cond, mutex);     unlockmutex(mutex); } 

i don't have deadlock, unfortunatelly doesn't work expected. can give me explanation should do? grateful help.

the problem thread setting *variable = 1 before of sleeping threads have chance see 0. because condition variable wake waiting threads doesn't mean woken threads scheduled fast enough prevent thread writing *variable again.