C语言多线程 pthread_create 的用法详解与示例

最近在学习 pthread 多线程编程,遇到了 pthread_create 函数的使用问题,结合一段简单代码做了一些总结,分享给大家,帮助理解线程函数的写法、参数传递方式以及多线程运行的基本机制。

一、为什么线程函数要写成 void *thread_callback(void *arg)

使用 pthread_create 创建线程时,线程函数必须遵循固定格式:

void *函数名(void *参数)

这是 POSIX 线程库 的要求。该函数:

  • 只能接收一个参数;

  • 参数类型必须是 void *(通用指针);

  • 返回值也必须是 void *(虽然很多时候用不到)。

这种设计是为了通用性:你可以通过 void * 传入任意类型的数据(如 int *、结构体指针等),只需要在函数内部自行类型转换。

二、怎么把自己的变量传进去线程函数?

int count = 0; 为例,若要在线程中操作这个变量,应该传它的地址 &count 进去:

pthread_create(&tid, NULL, thread_callback, &count);

线程函数定义为:

void *thread_callback(void *arg) {
    int *pcount = (int *)arg;  // 将通用指针强制转换为实际类型指针
    ...
}

这样,线程就可以通过 *pcount 直接修改主线程的 count 变量,实现数据共享。

三、pthread_create 函数原型与参数说明

int pthread_create(pthread_t *thread,
                   const pthread_attr_t *attr,
                   void *(*start_routine)(void *),
                   void *arg);

参数解释如下:

参数 含义
pthread_t *thread 用于存储新线程的线程 ID
const pthread_attr_t *attr 线程属性,设为 NULL 使用默认属性
void *(*start_routine)(void *) 线程函数(入口),必须是 void* 形式
void *arg 传递给线程函数的参数(可传任意指针)

四、完整示例代码

下面是一段使用 pthread_create 创建 10 个线程的示例,所有线程同时对一个全局变量 count 执行加一操作:

#include 
#include 
#include 

#define THREAD_COUNT 10

void *thread_callback(void *arg) {
    int *pcount = (int *)arg;
    int i = 0;
    while (i++ < 100000) {
        (*pcount)++;        // 修改主线程中的 count
        usleep(1);          // 稍微休眠,避免线程抢占 CPU 过猛
    }
    return NULL;
}

int main() {
    pthread_t threadid[THREAD_COUNT] = {0};
    int count = 0;

    for (int i = 0; i < THREAD_COUNT; i++) {
        pthread_create(&threadid[i], NULL, thread_callback, &count);
    }

    // 主线程每秒打印一次 count 值,共打印 100 次
    for (int i = 0; i < 100; i++) {
        printf("count : %d\n", count);
        sleep(1);
    }

    return 0;
}

五、编译指令说明

在 Linux 系统下,编译时 必须加上 -lpthread,否则会出现 undefined reference to pthread_create 错误:

gcc -o Lock Lock.c -lpthread

-lpthread 表示链接 POSIX 线程库。

https://github.com/0voice

你可能感兴趣的:(c语言,开发语言)