Linked Questions

Popular Questions

I have successfully implemented a producer thread and 2 worker threads or consumer threads.

The producer thread broadcasts condition using pthread_cond_broadcast. And the worker threads are blocked by pthread_cond_wait.

The code looks something likes this:

Thread 1 (Producer Thread):

pthread_mutex_lock
pthread_cond_broadcast
pthread_mutex_unlock

Thread 2 (Worker/Consumer Thread):

work = 1
while(1)
{
  pthread_mutex_lock
  while(!work)
  {
    work = 1;
    pthread_cond_wait
  }

  // Thread operation
  work = 0;
  pthread_mutex_unlock
}

Thread 3 (Worker/Consumer Thread):

work = 1
while(1)
{
  pthread_mutex_lock
  while(!work)
  {
    work = 1;
    pthread_cond_wait
  }

  // Thread operation
  work = 0;
  pthread_mutex_unlock
}

My question is why does Thread 2 or Thread 3 does not re-execute itself ?

In other words, when the condition was broadcasted by Thread 1, lets say Thread 2 unblocks on the condition first, performs thread operation and calls thread_cond_wait and blocks itself.

Now Thread 3 unblocks on the condition, performs thread operation and calls thread_cond_wait and block itself.

At this point of time, both the threads are blocked waiting for the condition, so is the condition variable reset ? If so, how does it know when to reset, as instead of 2 worker threads, I could have 5 worker threads ?

Why doesn't Thread 2 and Thread 3 unblock themselves again for the same condition ?

I wanted to know the internal mechanism, about how the threads unblock for a particular condition only once, not again, until a new broadcast is sent.

I have tried to read about this, but all I could see was, if a condition broadcast is sent, all threads waiting for that condition are unblocked. What I don't understand is why does the same thread not unblock for the same condition multiple times ?

I have tried looking at the pthread_cond_t, but could not get any clue.

Any help or suggestion about what I am lacking or thinking wrong, will be appreciated.

Thanks

Related Questions