带返回值的pthread函数基础用法:C语言线程统计文件行数问题求助
问题修正说明
现有代码的核心问题
- 线程函数签名不符合pthread规范:pthread要求入口函数必须返回
void*,参数类型为void*,你当前定义的int count_lines(int *fh)签名完全不匹配,同时传入的参数是FILE*的地址,接收用int*类型也完全错误。 - 线程返回值接收逻辑错误:
pthread_join的第二个参数需要传入void*类型变量的地址,用来存储线程返回的void*值,你直接把int类型的linecount强转为void**属于非法内存访问,必然报错。 - 隐藏问题1:
fopen打开文件后没有判断是否打开成功就直接传入线程,存在空指针风险。 - 隐藏问题2:
count_lines中判断fh为空时,错误地把文件指针当做字符串传入printf的%s占位符,会触发段错误。
修正后的代码
main.c
#include <stdio.h> #define MAX_FILE_NAME 100 #include "t_func.h" #include <pthread.h> int main(){ int linecount; pthread_t thread_id; FILE *fh = fopen("/home/usr154/out.log", "r"); // 新增文件打开失败判断 if (fh == NULL) { printf("打开文件失败\n"); return -1; } pthread_create(&thread_id, NULL, count_lines, fh); // 修正返回值接收逻辑,传入linecount的地址 pthread_join(thread_id, (void **)&linecount); printf("lines: %d \n", linecount); return 0; }
t_func.h
#include <stdlib.h> #include <stdio.h> // 修正函数签名符合pthread接口要求 void* count_lines(void* arg){ // 转换参数为正确的FILE*类型 FILE* fh = (FILE*)arg; int count = 0; char c; if (fh == NULL) { printf("传入的文件指针为空\n"); return (void*)0; } for (c = getc(fh); c != EOF; c = getc(fh)) { if (c == '\n') count++; } fclose(fh); // 把统计结果转为void*类型返回 return (void*)count; }
编译注意事项
编译时需要链接pthread库,编译命令参考:gcc main.c -o linecount -lpthread
内容的提问来源于stack exchange,提问作者porgrammer3124
相关产品推荐
相关产品推荐

