【问题标题】:How to Return Values From thread Back to main()如何将值从线程返回到 main()
【发布时间】: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。当我运行上面的代码时,我得到一个“核心转储(分段错误)”错误。再次感谢您的帮助。

【问题讨论】:

  • 编译器应该转储警告,不要忽略它们。
  • printfgetc 是 C 函数,但您包含 C++ 标头 &lt;iostream&gt;。您应该使用一种语言,而不是混合使用两种语言。这甚至是编译器,这纯属巧合。
  • Visual Studio 代码不能与 pthread 一起使用,所以我必须使用终端并且终端不会引发警告
  • 您使用 C 还是 C++?当您不询问差异、相似之处、如何创建代码以在两者中工作或类似的事情时,请不要同时使用这两个标签。
  • @MSalters printf()getc() 也是 C++ 函数。我并不是说它们应该在 C++ 中使用,但正确使用它们是有效且定义明确的。

标签: c multithreading pthreads pthread-join


【解决方案1】:

你让一切变得不必要的复杂。制作一个这样的结构:

typedef struct
{
  FILE* fp;
  int   ret_val;
} count_lines_type;

static count_lines_type cl;
cl.fp = fopen (...);
...
pthread_create(&my_thread, NULL, count_lines, &cl);

在线程完成之前填写ret_val

我创建了结构实例static,以防调用线程在计数线程完成之前超出范围。如果它从不这样做,static 就没有必要了。

【讨论】:

    【解决方案2】:

    在创建线程之前,检查文件是否真的被打开:

    fh=fopen("data.txt", "r");
    if (fh == NULL) exit(1);
    

    fh 也已经是一个指针。您不需要将 &fh(指向指针的指针)传递给 thred create(您在 count_lines 中期望 FILE* 而不是 FILE**)。 还要检查线程创建是否成功:

     if (pthread_create(&my_thread, NULL, count_lines, fh) != 0)
        exit(2);  //error -> contents of my_thread is undefined in this case
    

    还要检查 retval(仅当指针有效时取消引用,否则分段错误):

    if (retval != NULL)
    {
       int i = *((int *)retval);
       free(retval);
    }
    

    【讨论】:

    • 文件已打开,我认为 malloc() 发生了一些事情,但我不知道是什么
    猜你喜欢
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多