【发布时间】:2021-01-05 03:06:27
【问题描述】:
我正在使用 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。当我运行上面的代码时,我得到一个“核心转储(分段错误)”错误。再次感谢您的帮助。
【问题讨论】:
-
编译器应该转储警告,不要忽略它们。
-
printf和getc是 C 函数,但您包含 C++ 标头<iostream>。您应该使用一种语言,而不是混合使用两种语言。这甚至是编译器,这纯属巧合。 -
Visual Studio 代码不能与 pthread 一起使用,所以我必须使用终端并且终端不会引发警告
-
您使用 C 还是 C++?当您不询问差异、相似之处、如何创建代码以在两者中工作或类似的事情时,请不要同时使用这两个标签。
-
@MSalters
printf()和getc()也是 C++ 函数。我并不是说它们应该在 C++ 中使用,但正确使用它们是有效且定义明确的。
标签: c multithreading pthreads pthread-join