1
votes

I have encountered a problem while implementing wait and signal conditions on multiple threads.

A thread needs to lock a mutex and wait on a condition variable until some other thread signals it. In the meanwhile, another thread locks the same mutex and waits on the same condition variable. Now, the thread which is running concurrently throughout the process signals the condition variable but I want only the first thread that is waiting must be signalled and not the others.

3

3 Answers

5
votes

If two threads wait on the same condition variable, they must be prepared to handle the same conditions, or you must carefully construct your program so they are never waiting on the condition variable at the same time.

Why does this notification have to be handled by the first thread and not the second?

You may be better off with two separate condition variables.

2
votes

Use pthread_cond_signal() to wake up one of the threads.

However, more than one might be awoken; this is termed spurious wakeup. You need a variable to track your application state, as described in the manual page linked above.

0
votes

Your requirement is impossible. You say "... I want only the first thread that is waiting must be signalled and not the others." But condition variables never, ever provide any way to ensure a thread isn't signaled. So if you have a requirement that a thread must not be signaled, you cannot use condition variables.

You must always use a condition variable like this:

while(NotSupposedToRun)
  pthread_cond_wait(...);

So if the thread wakes up when it's not supposed to, the while is still false and the thread just goes back to sleep. This is mandatory because POSIX does not ever provide any guarantee that a thread won't be woken. An implementation is perfectly free to implement pthread_cond_signal as a call to pthread_cond_broadcast and unblock all threads on every signal if it wants to.

Because condition variables are stateless, the implementation never knows whether a thread is supposed to be woken or not for sure. It is your job to call pthread_cond_wait always, and only, when a thread should not be running.

See http://en.wikipedia.org/wiki/Spurious_wakeup for more details.

If you cannot precisely specify the wakeup conditions for each thread in a while loop like the one above, you should not be using condition variables.