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

标签 multithreading pthreads condition-variable

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

Note that the pthread_cond_wait routine will automatically and atomically unlock mutex while it waits.

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

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 呢?上面的代码结束了吗?

我错过了什么?

最佳答案

pthread_cond_wait解除阻塞时,它再次持有锁。举例来说,您循环两次,在互斥体上获得以下锁定/解锁序列:

lock

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

# loop done, still holding lock

unlock

如果您没有最后一次解锁,那么下次其他人想要获取锁时,您将陷入死锁。

关于multithreading - pthread_cond_wait 在等待时自动并原子地解锁互斥体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11062701/

相关文章:

c++ - 线程安全的 TBB::concurrent_hash_map 删除

c++ - 等待其他线程继续

CURLcode 到 C 中的变量

c - Linux 中的 Pthread

c++ - 如果从 C 源而不是 C++ 源调用 pthread_exit,取消处理程序将不会运行

c++ - std::condition_variable::notify_one() 不唤醒等待线程

java - 使用 2 个不同的类打印偶数和奇数

c# - WCF PerCall 共享资源锁问题

multithreading - pthread_cond_timedwait 超时后线程是否拥有互斥锁?

c++ - 条件变量函数未在此范围内声明