如何检测所有线程均阻塞在pthread_cond_wait并优雅终止任务队列程序
问题原因分析
- 原代码工作线程采用死循环逻辑,没有设置退出触发条件,即便无任务可处理也不会主动终止
- 当
moreTasks减为0后不会再生成新任务,任务队列清空后所有线程都会永久阻塞在pthread_cond_wait调用,既没有新的唤醒信号,也没有退出通知 - 你尝试的等待线程计数器方案是可行的,只需要结合「无新任务生成」「所有线程都处于等待状态」两个判断条件做退出触发即可
修复方案
需要新增2个全局变量配合逻辑调整,所有变量的读写操作都需要在持有队列锁的场景下执行,避免竞态问题:
int shutdown = 0; // 线程池退出标记 int waiting_threads = 0; // 统计当前阻塞在条件等待的线程数量
核心调整点
- 线程进入条件等待前累加等待计数,被唤醒后先判断是否触发了退出标记,是则直接终止线程
- 每次任务队列为空时,检查终止条件:无剩余待生成任务 + 所有线程都在等待,满足则设置退出标记并广播唤醒所有等待线程
- 调整
moreTasks的判断和修改逻辑,全部放在锁内执行,避免多线程并发读写的竞态问题
修改后完整代码
#include <stdio.h> #include <string.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #define THREAD_NUM 4 typedef struct Task { int a, b; } Task; Task taskQueue[256]; int taskCount = 0; int moreTasks = 10; // 新增变量 int shutdown = 0; int waiting_threads = 0; pthread_mutex_t mutexQueue; pthread_cond_t condQueue; void executeTask(Task *task) { usleep(50000); int result = task->a + task->b; printf("The sum of %d and %d is %d\n", task->a, task->b, result); // 调整moreTasks操作,全部放在锁内避免竞态 pthread_mutex_lock(&mutexQueue); if (moreTasks > 0) { moreTasks--; pthread_mutex_unlock(&mutexQueue); Task t = { .a = rand() % 100, .b = rand() % 100}; submitTask(t); } else { pthread_mutex_unlock(&mutexQueue); } } void submitTask(Task task) { pthread_mutex_lock(&mutexQueue); taskQueue[taskCount] = task; taskCount++; pthread_mutex_unlock(&mutexQueue); pthread_cond_signal(&condQueue); } void *startThread(void *args) { while (1) { Task task; pthread_mutex_lock(&mutexQueue); while (taskCount == 0 && !shutdown) { waiting_threads++; // 检查是否满足终止条件:无更多任务生成 + 所有线程都在等待 if (moreTasks == 0 && waiting_threads == THREAD_NUM) { shutdown = 1; pthread_cond_broadcast(&condQueue); } pthread_cond_wait(&condQueue, &mutexQueue); waiting_threads--; } // 退出判断 if (shutdown) { pthread_mutex_unlock(&mutexQueue); pthread_exit(NULL); } task = taskQueue[0]; int i; for (i = 0; i < taskCount - 1; i++) { taskQueue[i] = taskQueue[i + 1]; } taskCount--; pthread_mutex_unlock(&mutexQueue); executeTask(&task); } } int main(int argc, char *argv[]) { pthread_t th[THREAD_NUM]; pthread_mutex_init(&mutexQueue, NULL); pthread_cond_init(&condQueue, NULL); int i; for (i = 0; i < THREAD_NUM; i++) { if (pthread_create(&th[i], NULL, &startThread, NULL) != 0) { perror("Failed to create the thread"); } } srand(time(NULL)); for (i = 0; i < 100; i++) { Task t = { .a = rand() % 100, .b = rand() % 100}; submitTask(t); } for (i = 0; i < THREAD_NUM; i++) { if (pthread_join(th[i], NULL) != 0) { perror("Failed to join the thread"); } } pthread_mutex_destroy(&mutexQueue); pthread_cond_destroy(&condQueue); return 0; }
内容的提问来源于stack exchange,提问作者Smiley
相关产品推荐
相关产品推荐

