Zohar81 Zohar81 - 2 years ago 63
C Question

How to avoid waiting for pthread_cond_t where signal already sent

I've got a logic inside a dynamic library that run some service that is requested by the main executable.

Upon calling

from the library code, some preparation is required prior to service ready, and during this time, the main code should not try to access the service.

To notify the main code when the service is ready I use conditional variable and signal the main executable.

I'd like to hear some advices about the best way to handle a situation when the library become serviceable BEFORE the main code wait for the conditional variable. in this case, the waiting can last forever...

here's the service code :

extern pthread_cond_t cnd;
extern pthread_mutex_t mtx;

void start_service()
// getting serviceable.

And here's the main code.

pthread_cond_t cnd;
pthread_mutex_t mtx;

int main()
pthread_mutex_init(&mtx, NULL);

std::thread mytrd(&start_service);

pthread_cond_wait(&cnd, &mtx); // what happens if we get here after the signal already sent.

P.S the desired behavior should be that the main code avoid waiting for the conditional variable if it's already signaled.

Answer Source

You need a predicate and enclose the wait in a check for the predicate:

    while( ! predicate ) pthread_cond_wait(&cnd, &mtx);  

In this way, the thread doesnt event start to wait when it doesnt need to. The second reason you need this is to avoid spurious wakeups thay may occur, ie pthread_cond_wait may return even if the other thread did not signal the condition.

The other thread then has to do (you need to lock the mutex to protect the predicate):

 predicate = true;  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download