Reputation: 21615
Say the broadcasting thread broadcasts while only 3 threads are waiting and the 4th thread call pthread_cond_wait
after the broadcasting thread is done with broadcast, will the 4th thread ever get out of the waiting condition. And how is the condition variable reset, so that the broadcasting thread can rebroadcast sometimes later to the waiting threads.
Upvotes: 1
Views: 4108
Reputation: 279255
will the 4th thread ever get out of the waiting condition
No, not until there's another broadcast or signal.
And how is the condition variable reset, so that the broadcasting thread can rebroadcast sometimes later to the waiting threads.
It's simplest to imagine that everything that a condition variable does, is synchronized under the mutex associated with the condition variable. So at the time you broadcast, everything waiting is (somehow) put into a state where it is trying to wake up and take the mutex. Then, the broadcasting thread releases the mutex. So it's not really the condition variable that's "reset" when you broadcast, it's the first three threads that are moved from waiting on the condition variable, to waiting on the mutex.
In order to wait on the condvar, your 4th thread must first acquire the mutex. This might happen before or after the first three threads manage to wake up and take the mutex, but it clearly happens after the broadcast, and so your 4th thread is not in "trying to wake up" state, it's in "waiting for a signal or broadcast" state.
Actually it's more complicated than that -- you don't actually have to hold the mutex in order to broadcast a condition variable. So condition variables must include some additional internal synchronization (I don't know the specific details on linux), to make sure that all threads waiting before the broadcast get their state changed as a single operation.
Normally you might as well hold the mutex to broadcast, though, because you broadcast when you've just changed something that waiters want to see, and whatever that thing is that's looked at from lots of threads, is synchronized using the mutex. And there are a couple of awkward situations that you can avoid by always doing it that way.
Upvotes: 3
Reputation: 500357
will the 4th thread ever get out of the waiting condition.
No, not unless the condition variable is signalled while thread 4 is waiting.
The man page explains:
The
pthread_cond_broadcast()
call unblocks all threads currently blocked on the specified condition variablecond
.The
pthread_cond_signal()
andpthread_cond_broadcast()
functions have no effect if there are no threads currently blocked oncond
.
Upvotes: 1