CHID
CHID

Reputation: 1643

Pthread condition wait and signal

I have a doubt regarding pthread_cond_wait and pthread_cond_signal functions. I was not able to understand after reading the man pages also.

Please consider the following code.

void* thread_handler(){
... // counts till COUNT_LIMIT is reached
if (count == COUNT_LIMIT) {
  pthread_cond_signal(&count_threshold_cv);
  printf("inc_count(): thread %ld, count = %d  Threshold reached.\n",
         my_id, count);
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\n",
       my_id, count);
...
}

void* thread_handler1(){
... // waits till the previous thread has finished counting
pthread_mutex_lock(&count_mutex);
while (count<COUNT_LIMIT) {
   pthread_cond_wait(&count_threshold_cv, &count_mutex);
   printf("watch_count(): thread %ld Condition signal received.\n", my_id);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(NULL);
}

The code is working as per expectations. I am trying to understand the code. Here is how the program works

  1. Enter thread_handler1 and do cond_wait. From the man page i understood that cond_wait will immediatly release the lock atomically. So why are they releasing the lock again below in thread_handler1

  2. After first thread has satisfied the condition and hits the condition signal I expected the thread which was blocking to execute its steps. Instead i got the printfs below the thread which executed the cond_signal. Why is this happening

  3. Overall why do we need to take a lock before waiting and signalling. Cant this be done without a lock.

For a briefer look at the program, please see the Complete program here. You can find it under the section "Using Conditional Variables"

Thanks in advance

Chidambaram

Upvotes: 0

Views: 4403

Answers (1)

Tudor
Tudor

Reputation: 62439

Enter thread_handler1 and do cond_wait. From the man page i understood that cond_wait will immediatly release the lock atomically. So why are they releasing the lock again below in thread_handler1

Because the thread that is supposed to wait will release the lock when calling wait, but will then reacquire after it gets signaled (when it becomes available). That's why you need to rerelease it explicitly later.

After first thread has satisfied the condition and hits the condition signal I expected the thread which was blocking to execute its steps. Instead i got the printfs below the thread which executed the cond_signal. Why is this happening

Because calling signal does not switch the thread from the CPU. It will continue to run normally.

Upvotes: 2

Related Questions