I've got a logic inside a dynamic library that run some service that is requested by the main executable.
extern pthread_cond_t cnd;
extern pthread_mutex_t mtx;
// getting serviceable.
pthread_cond_wait(&cnd, &mtx); // what happens if we get here after the signal already sent.
You need a predicate and enclose the
wait in a check for the predicate:
pthread_mutex_lock(&mtx); while( ! predicate ) pthread_cond_wait(&cnd, &mtx); pthread_mutex_unlock(&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):
pthread_lock_mutex(&mtx); predicate = true; pthread_cond_signal(&cnd); pthread_unlock_mutex(&mtx);