RVR
RVR

Reputation: 13

pthread_cond_broadcast unblocks a thread not waiting on conditional variable

I'm working with POSIX and I've 3 threads.

Please note all the threads below uses the same mutex lock.

Thread 1 is waiting using pthread_cond_wait for a condition to be met(the wait is within a while loop, so its not an unconditional wait too). Thread 2 is going to issue a pthread_cond_broadcast when condition is met. Thread 3 uses the mutex for locking but doesn't wait on the conditional variable.

So, thread 1 is waiting for signal/broadcast and thread 3 is waiting for the mutex lock(this thread is just waiting to acquire mutex lock). Now if thread 2 sends a broadcast, somehow thread 3 is acquiring the mutex instead of thread 1. Why would this happen? I'm using debian 8.3 using glibc2.19. Shouldn't the broadcast wake up the thread which was waiting on the conditional variable?

Upvotes: 0

Views: 557

Answers (1)

ixSci
ixSci

Reputation: 13698

I assume you have a mutex locked in thread 2(other way your question doesn't make sense). So when you call pthread_cond_broadcast it just unblocks the threads which are waiting on the conditional variable. No execution transfer is happening.

Then you unblock the mutex and expect that the thread which was waiting should be scheduled. But this expectation is wrong because it is up to the scheduler to decide what the next thread to schedule and you also have Thread 3 unblocked since the mutex is not locked any more. So it is up to scheduler to decide which one(1 or 3) will be run next. Nothing constrains it in this situation.

Upvotes: 1

Related Questions