pthread-w32 之 pthread_cond_wait 问题

这篇博客介绍了在Windows下使用pthread-w32时遇到的pthread_cond_wait函数导致的死锁问题。作者通过跟踪分析发现,问题源于ptw32_cleanupKey未正确初始化。解决方案是在main函数中调用pthread_once进行初始化。文章引用了相关资源并提供了参考资料。
摘要由CSDN通过智能技术生成

pthread-w32 之 pthread_cond_wait 问题

前言

  • 之前在别的项目中,发现 pthread_cond_wait 只触发一次,一直是“绕行”解决,Linux和Win32代码在这里不同步。最近,又一次需要 pthread_cond_wait 方案,不爽之余,勉力着手解决。

问题

  • 第二次 pthread_cond_wait 时函数“死锁”

  • 测试代码

    测试代码来自 POSIX Threads Programming;该例子只触发一次 pthread_cond_wait 就退出循环,本文为了测试多次触发 pthread_cond_wait,有小改动。

      /**!
      * \Copyright All copyright reserved 2010 - 2021
      * \Brief     
      * \Source	https://hpc.llnl.gov/training/tutorials
      * \Source   https://hpc-tutorials.llnl.gov/posix/example_using_cond_vars/
      **/
      #include <stdio.h>
      #include <stdlib.h>
      #ifdef   _MSC_VER
      #include <winsock2.h>
      #include <windows.h>
      #pragma comment(lib, "ws2_32.lib")
      #endif
    
      #include <pthread.h>
    
      #define NUM_THREADS  3
      #define TCOUNT 10
      #define COUNT_LIMIT 12
    
      int     count = 0;
      pthread_mutex_t count_mutex;
      pthread_cond_t count_threshold_cv;
    
      void *inc_count(void *t)
      {
         
          int i;
          long my_id = (long)t;
    
          for (i = 0; /*i < TCOUNT*/(count < COUNT_LIMIT); i++)
          {
         
              pthread_mutex_lock(&count_mutex);
              count++;
              /*
              Check the value of count and signal waiting thread when condition is
              reached.  Note that this occurs while mutex is locked.
              */
              printf("inc_count(): thread %ld, count = %d  Threshold reached. ", my_id, count);
              pthread_cond_signal(&count_threshold_cv);
              printf("Just sent signal.\n");
              //printf("inc_count(): thread %ld, count = %d, unlocking mutex\n", my_id, count);
              pthread_mutex_unlock(&count_mutex);
    
              /* Do some work so threads can alternate on mutex lock */
              usleep(500 * 1000);
          }
          pthread_exit(NULL);
          printf("inc_count(): thread %ld, count = %d done "
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值