我正在学习线程并尝试实现创建线程的代码。线程写入文件。如果线程已创建,则 返回 0
。此处的代码返回 0
但它确实进入函数 write()
但不写入文件。只是为了检查它是否进入函数,我已经放置了一个 printf()
语句。我希望这里的输入应该由命令行获取,但它也不起作用所以为了让它更简单我只写了“ Hello World ”到文件。
这是代码:-
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *write(void *arg)
{
printf("HI \n");
FILE *fp;
fp = fopen("file.txt", "a");
if (fp == NULL) {
printf("error\n");
} else {
fprintf(fp, "hello world");
}
}
int main()
{
pthread_t thread;
int tid;
tid = pthread_create(&thread, NULL, write, NULL);
printf("thread1 return %d \n", tid);
exit(0);
}
最佳答案
我怀疑正在发生的事情是在 fprintf() 将内容放入缓冲区之前执行 exit() 调用。
pthread_create() 在创建线程之后返回,而不是在线程结束之后返回,然后两个线程同时运行。也许这是您的第一个“竞争条件”?
void *result; pthread_join(tid, &result);
将等待在另一个线程中运行的函数返回(并获取它的返回值)。
更正 忘了文件指针不会自动关闭,所以这也会阻碍你。在 fprintf 之后调用 fflush() 或 fclose()。
关于创建写入文件的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18425801/