C语言 pthread_create() 函数详解与多线程编程指南

今天早睡
今天早睡
发布时间:2026-10-13 | 6人浏览过
原创

本文深入解析C语言中用于创建线程的 pthread_create 函数。详细阐述其头文件引用、函数原型、各参数含义及返回值机制,重点说明在Linux环境下需显式链接 -lpthread 库。通过完整示例代码展示线程标识符获取与线程创建过程,帮助开发者掌握POSIX线程接口的核心用法。

pthread_create() 函数详解

pthread_create 是类 Unix 操作系统(包括 Unix、Linux、Mac OS X 等)中用于创建线程的标准函数。该函数的主要功能是确定新线程的执行入口点,即指定调用线程函数的起始位置。一旦线程创建成功,系统便会调度该线程开始执行相关的线程函数逻辑。

在使用该函数前,需包含相应的头文件:

#include<pthread.h>

函数原型如下:

int pthread_create (pthread_t * tidp,     const pthread_attr_t * attr,    void * (*start_rtn)(void*),      void *arg);
各参数详细说明:
第一个参数为指向线程标识符的指针(tidp)。
第二个参数用于设置线程属性(attr)。
第三个参数指定线程运行函数的起始地址(start_rtn)。
最后一个参数为运行函数所需的参数(arg)。
编译与链接时需使用的参数:
-lpthread
返回值机制:

若线程创建成功,函数返回 0;若创建失败,则返回错误编号,此时 *thread 指针指向的内容为未定义状态。

    当返回成功时,由 tidp 指向的内存单元将被设置为新创建线程的线程 ID。attr 参数用于指定各种线程属性。新创建的线程将从 start_rtn 函数的地址开始执行,该函数接收一个 void* 类型的万能指针参数 arg。若需向 start_rtn 传递多个参数,需将这些参数封装到一个结构中,并将该结构的地址作为 arg 传入。
    在 Linux 系统下使用 C 语言开发多线程程序时,系统遵循 POSIX 线程接口,该接口被称为 pthread。
注意事项:
    由于 pthread 并非 Linux 系统的默认库,而是 POSIX 线程库,因此在编译时需显式链接该库,即添加 -lpthread(或 -pthread)选项。当函数执行出现错误时,错误信息将作为返回值返回,而不会修改系统全局变量 errno,因此无法直接使用 perror() 函数打印错误信息。
示例代码:
输出线程标识符:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>


void printids(const char *s)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int) pid, (unsigned int) tid, (unsigned int) tid);

}

void * thr_fn(void *arg)
{
printids("new thread: ");
return NULL;
}

int main()
{
int err;
pthread_t ntid;
err = pthread_create(&ntid, NULL, thr_fn, NULL);
if(err != 0)
{
printf("Can't create thread: %s\n", strerror(err));
}

printids("main thread");
pthread_join(ntid, NULL);

return EXIT_SUCCESS;
}

运行结果展示:

至此,关于 C 语言 pthread_create() 函数的讲解已结束。如需了解更多 C 语言相关内容,建议查阅本站过往文章或继续浏览后续系列教程,感谢大家的支持。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表