使用pthreads时随机触发Segmentation Fault的原因排查
问题分析与解决方案
你的代码出现随机段错误的核心原因是未初始化互斥锁,另外还有线程函数未返回值的小问题,具体分析和修复如下:
问题根源
- 未初始化互斥锁:全局变量
pthread_mutex_t mtx仅完成声明,未通过pthread_mutex_init或静态初始化宏PTHREAD_MUTEX_INITIALIZER完成初始化。直接对未初始化的互斥锁执行lock/unlock操作会触发未定义行为,表现为随机崩溃或输出异常。 - 线程函数无返回值:
test_thread_function作为pthread的入口函数,必须返回void*类型值,当前代码缺少返回语句,可能导致线程退出时的未定义行为。
修复步骤
1. 初始化互斥锁
有两种可靠方式:
- 静态初始化:声明时直接赋值
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; - 动态初始化:在
main函数开头调用初始化接口,程序结束前销毁锁int main() { pthread_mutex_init(&mtx, NULL); // ... 其他代码 pthread_mutex_destroy(&mtx); }
2. 给线程函数添加返回值
在test_thread_function末尾添加return NULL;语句。
修改后的完整代码
#include <iostream> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> using namespace std; #define NUM_THREADS 2 // 静态初始化互斥锁 pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; struct Args { int tid; string type; }; void *test_thread_function(void *args) { Args *local_args = (Args *)args; pthread_mutex_lock(&mtx); cout << "Printing from thread " << local_args->tid << endl; cout << "Value of type is " << local_args->type << endl; pthread_mutex_unlock(&mtx); // 添加返回值 return NULL; } int main() { pthread_t threads[NUM_THREADS]; Args per_thread_args[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { if (i == 0){ per_thread_args[i].tid = 0; per_thread_args[i].type = "barber"; pthread_create(&threads[i], NULL, test_thread_function, (void *)&per_thread_args[i]); } else { per_thread_args[i].tid = 1; per_thread_args[i].type = "customer"; pthread_create(&threads[i], NULL, test_thread_function, (void *)&per_thread_args[i]); } } void *ret; for (int i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], &ret); } // 销毁互斥锁(静态初始化也建议销毁,是良好编程习惯) pthread_mutex_destroy(&mtx); return 0; }
编译运行注意事项
编译时必须链接pthread库,例如使用g++:
g++ your_code.cpp -o your_program -lpthread
内容的提问来源于stack exchange,提问作者user14502070
相关产品推荐
相关产品推荐

