如何在pthread_create()中向函数指针传递参数?
pthread线程代码修正方案
核心问题分析
你遇到的错误源于两个关键点:
pthread_create要求线程函数必须是void* (*)(void*)类型的函数指针,你的match函数签名不匹配- 直接调用
match(i, conv)是执行函数而非传递指针,导致编译器报错
具体修改步骤
调整线程函数签名
将match函数改为符合pthread规范的签名:返回void*,参数为单个void*指针,内部再将参数转成自定义结构体类型。定义参数结构体
创建一个结构体来封装线程需要的两个参数(线程ID、目标数字),这样就能通过单个指针传递多个数据。修正pthread_create调用
第三个参数直接传match(函数名本身就是指针),第四个参数传入封装好的结构体指针;同时要为每个线程单独分配结构体内存,避免多个线程共享同一个结构体的竞态问题。修复循环变量问题
循环创建线程时,不能直接使用循环变量i传递给线程(线程启动后可能i已经被修改),必须将i的值存入结构体,确保每个线程拿到自己的ID。补充必要细节
线程函数最后返回NULL满足返回值要求;给printf加上换行符,避免输出内容混乱。
修正后的完整代码
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> // 定义线程参数结构体 typedef struct { int thread_id; int target_num; } ThreadArgs; void* match(void* args) { ThreadArgs* thread_args = (ThreadArgs*)args; int id = thread_args->thread_id; int number = thread_args->target_num; for(;;){ int random = 1 + (rand() % 9999); if(random == number) break; } printf("Thread number %d has completed.\n", id); // 释放参数结构体内存 free(args); return NULL; } int main (int argc, char *argv[]){ if (argc < 2) { fprintf(stderr, "Usage: %s <target-number>\n", argv[0]); return 1; } int conv = atoi(argv[1]); pthread_t th[10]; int i; for (i = 0; i < 10; i++){ // 为每个线程分配参数结构体 ThreadArgs* args = malloc(sizeof(ThreadArgs)); if (!args) { perror("Failed to allocate memory for thread args"); return 1; } args->thread_id = i; args->target_num = conv; if(pthread_create(&th[i], NULL, match, args) != 0){ perror("Failed to create thread"); free(args); // 创建失败时释放内存 return 1; } } for (i = 0; i < 10; i++){ if (pthread_join(th[i], NULL) != 0){ perror("Failed to join thread"); return 2; } } return 0; }
额外提示
rand函数不是线程安全的,如果需要更高的线程安全性,可以使用rand_r或者其他线程安全的随机数生成函数。- 主线程中必须用
pthread_join等待所有线程执行完毕,否则主线程提前退出会导致子线程被强制终止。
内容的提问来源于stack exchange,提问作者TheIncrediblyStupidOne
相关产品推荐
相关产品推荐

