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 "