pthread_cond_wait在等待时自动并原子地解锁互斥锁

时间:2012-06-16 10:40:10

标签: multithreading pthreads condition-variable

从这里开始:https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal

  

请注意pthread_cond_wait     例程会在等待时自动和原子地解锁互斥锁。

以下子代码来自同一个链接(由我格式化):

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);
      count += 125;
      printf("watch_count(): thread %ld count now = %d.\n", my_id, count);
  }

pthread_mutex_unlock(&count_mutex);  

问题:
当它说pthread_cond_wait会在等待时自动解锁互斥锁时,那么为什么我们必须明确在上面的代码末尾指定函数pthread_mutex_unlock

我错过了什么?

1 个答案:

答案 0 :(得分:4)

pthread_cond_wait取消阻止时,它再次按住锁定。比如说,你绕过循环两次,你会在互斥锁上获得以下锁定/解锁序列:

lock

# Around loop twice:
    wait (unlock)
    awaken (holding lock)
    wait (unlock)
    awaken (holding lock)

# loop done, still holding lock

unlock

如果您没有最后一次解锁,那么下次其他人想获得锁定时,您最终会陷入僵局。