问题描述
我正在使用pthread_create创建一个线程,该线程检查文件中的行数,然后将答案返回给主线程。我尝试使用pthread_join和malloc(),但是我对这两者都是新手,必须使用不当。如果有人知道如何将整数从线程传递回主线程,请提供帮助。我的代码在下面。
#include <pthread.h>
#include <stdio.h>
void *count_lines(void *arg)
{
FILE *fh= (FILE *) arg;
int num_lines=0;
char ch;
for(ch=getc(fh); ch!=EOF; ch=getc(fh))
if(ch=='\n')
num_lines=num_lines+1;
fclose(fh);
int* value = (int *)malloc(sizeof(int));
*value=10;
pthread_exit(value);
}
int main()
{
FILE *fh;
fh=fopen("data.txt","r");
pthread_t my_thread;
pthread_create(&my_thread,NULL,count_lines,&fh);
void *retval;
pthread_join(my_thread,&retval);
int i = *((int *)retval);
free(retval);
printf("%d\n",i);
}
我正在运行Ubuntu虚拟机并使用Visual Studio Code(如果有帮助的话)。当我运行上面的代码时,出现“ Core Dump(Segmentation Fault)”错误。再次感谢您的帮助。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)