Ubuntu20.04下运行简单pthread程序调用pthread_create出现段错误
段错误触发原因
核心错误:pthread_create 第一个参数传入空指针
pthread_create 函数的定义如下:
int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void *), void *restrict arg);
- 第一个参数
thread是输出参数,函数执行成功后会把新创建线程的ID写入该指针指向的内存空间。你直接传入NULL,导致函数尝试向空地址写入数据,触发空指针访问,直接抛出段错误。
修复方法
在main函数中定义一个pthread_t类型的变量存储线程ID,将该变量的地址作为第一个参数传入pthread_create即可,修复后的代码示例:
#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> // sleep函数需要该头文件,原代码遗漏可能引发编译警告 void* testfunc(void* arg) { while (1) { printf("testfunc\n"); // 加换行刷新缓冲区,避免看不到输出 } } int main(void) { printf("helo\n"); pthread_t tid; // 新增变量存储线程ID if (pthread_create(&tid, NULL, &testfunc, NULL) != 0) { perror("pthread failed to create\n"); } while (1) { printf("main function\n"); sleep(1000); } return 0; }
额外注意事项
- 编译时需要添加
-lpthread参数链接线程库,Ubuntu 20.04下正确编译命令为:gcc 你的源文件名.c -o 输出程序名 -lpthread,未加该参数会出现链接错误或者运行异常。 - 原代码中
printf("testfunc")没有换行符,标准输出为行缓冲模式,内容会停留在缓冲区不会打印到终端,添加换行符可以正常看到输出。
内容的提问来源于stack exchange,提问作者Iberico
相关产品推荐
相关产品推荐

