views:

76

answers:

3

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.

A: 

When one thread has locked the mutex, another can't lock it before the previous thread unlocks it.

Kedar Soparkar
The wait condition automatically unlocks the mutex and so, any other threads can use it.
Swaroop Vajrapu
pthread's signalling does not mean SIG*
Will
@Will, my mistake.
Kedar Soparkar
+3  A: 

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.

Anthony Williams
I am not sure about the number of threads as they are created using commands in a script file and each thread has separate functions though they work on the same variable.
Swaroop Vajrapu
@Swaroop: If the notification has really to be handled by the first thread, you need some kind of queue.
Jochen Walter
+2  A: 

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.

Will