Search code examples
cmultithreadingmutexwait

Explanation why conditional variable in C does not work correctly


I want to write a simple multithreaded program making use of conditional variables in C.

I want to have main thread (thread A) which sleeps 5 sec and then wake up waiting clients (therads B, possible many) that print a message. This should be repeated all the time.

I have already read the manual but I don't understand why this does not work. Let's assume that I have those variables given to all threads via pointers (properly, I have checked that):

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

I have the following code:

THREAD A (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, but unfortunatelly this doesn't work as I expected. Can somebody give me an explanation what should I do? I would be grateful for any help.


Solution

  • The likely problem is that Thread A is immediately setting *variable = 1 before any of the sleeping threads have a chance to see it as 0. Just because the condition variable will wake up waiting threads doesn't mean those woken threads will get scheduled fast enough to prevent Thread A from writing to *variable again.