如何将文件指针传递给pthread线程实现写入?当前无写入且无报错
问题分析与修复方案
核心问题
- 文件指针传递类型不匹配:
pthread_create中传递的是&outputFile(FILE**类型),但线程函数里直接将参数转为FILE*,导致写入操作指向错误内存地址。 - 主线程提前终止资源:主线程创建线程后立刻关闭文件并退出,此时子线程大概率未执行完成,即便执行,文件已被关闭,写入操作无效。
- 未定义变量引发未知行为:线程函数中的
r和globalValue未定义或初始化,会导致程序逻辑不可预测。
修复后的代码
#include <stdio.h> #include <pthread.h> // 示例初始化全局变量,实际项目建议用线程参数传递替代全局变量 int globalValue = 4; int r = 0; void *ThreadTwo(void *param){ // 正确转换参数类型为FILE* FILE *outputFile = (FILE*)param; if (r == 0) { fprintf(outputFile, "%d\n", globalValue); fprintf(outputFile, "%d\n", globalValue); printf("twice because it is even\n"); } else { fprintf(outputFile, "%d\n", globalValue); printf("Once because it is odd\n"); } pthread_exit(NULL); } int main() { FILE *outputFile; pthread_t th[1]; // 补全线程变量声明 outputFile = fopen("hw3.out", "w"); if (outputFile == NULL) { // 增加文件打开失败检查 perror("Failed to open file"); return 1; } // 直接传递FILE*类型的文件指针 pthread_create(&th[0], NULL, ThreadTwo, outputFile); // 等待子线程执行完毕再关闭文件 pthread_join(th[0], NULL); fclose(outputFile); return 0; }
关键修复说明
- 修正指针传递逻辑:
pthread_create最后一个参数直接传outputFile(FILE*类型),线程函数内正确转换参数类型。 - 阻塞等待线程完成:调用
pthread_join让主线程等待子线程执行结束,确保文件写入操作完成后再关闭文件。 - 添加错误检查:增加
fopen失败的判断逻辑,避免空指针操作。 - 补全变量声明与初始化:声明线程数组,初始化未定义的全局变量,保证程序逻辑可预测。
内容的提问来源于stack exchange,提问作者Mathew Cherian
相关产品推荐
相关产品推荐

