You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:27:00