0

Suppose I have 3 threads, A B and C, a pthread_mutex_t named mutex, and a pthread_cond_t named cond.

Threads B and C are blocking on a call to pthread_cond_wait(&cond, &mutex);.

Thread A locks the mutex, and calls pthread_cond_signal(&cond); twice before releasing the mutex.

Is this guaranteed to unblock both threads? More generally, if N threads are already waiting on a condition variable while pthread_cond_signal is called N times, can I assume that at least N waiting threads will be unblocked?

I don't have any specific use case for relying on this (maybe it'd be useful if you queue multiple tasks and want to make sure multiple worker threads wake to handle them?), but I'm trying to determine whether a specific implementation that doesn't make this guarantee can be correct.

Esme Povirk
  • 3,004
  • 16
  • 24

1 Answers1

1

Yes, if both B and C are blocked on the condition variable and no other threads are blocked on the condition variable, then calling pthread_cond_signal() twice with the mutex held is guaranteed to (eventually) wake them both up.

This follows directly from the requirement in POSIX:

The pthread_cond_signal() function shall unblock at least one of the threads that are blocked on the specified condition variable cond (if any threads are blocked on cond).

The first call to pthread_cond_signal() must unblock at least one of B and C, since those are the only threads blocked on the condition variable. Because the mutex remains held by the signalling thread, no other threads can block on the condition variable before the second call to pthread_cond_signal(), so the remaining one out of B and C (if only one of them was unblocked by the first call) must be unblocked by the second call.

caf
  • 233,326
  • 40
  • 323
  • 462