c - Pthread 条件等待和信号

标签 c linux multithreading pthreads

我对 pthread_cond_wait 和 pthread_cond_signal 函数有疑问。阅读手册页后我也无法理解。

请考虑以下代码。

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);
}

代码按预期运行。我试图理解代码。这是程序的工作原理

  1. 进入 thread_handler1 并执行 cond_wait。从手册页我了解到 cond_wait 将立即自动释放锁。 那他们为什么又在thread_handler1下面释放锁

  2. 在第一个线程满足条件并触发条件信号后 我希望被阻塞的线程执行它的步骤。相反,我在执行 cond_signal 的线程下面得到了 printfs。为什么会这样

  3. 总的来说,为什么我们需要在等待和发出信号之前锁定。这不能在没有锁的情况下完成。

要简要了解该程序,请参阅 Complete program这里。您可以在“使用条件变量”部分下找到它

提前致谢

奇丹巴拉姆

最佳答案

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

因为本应等待的线程会在调用 wait 时释放锁,但会在收到信号后(当它可用时)重新获取锁。这就是您稍后需要明确重新发布它的原因。

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

因为调用signal不会从CPU切换线程。它将继续正常运行。

关于c - Pthread 条件等待和信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13087398/

相关文章:

c - 下面的符号都指向什么?

php - cron 作业无法从 PHP 脚本运行

linux - 无法在linux中编译opencv

c++ - 在 Debian 8.7 上安装 g++ 7.0.1

需要 C# 线程帮助

c - 在 C 中从 stdio 扫描字符串和整数

c - 从结构中删除元素

c - 从 execv 启动终端 (sh) 返回错误 :/bin/sh:/bin/sh: cannot execute binary file

c - 等到上一个进程实例完成

Java - 线程基数排序