简体   繁体   English

如何从线程返回值返回到 main()

[英]How to Return Values From thread Back to main()

I am using pthread_create to create a thread that examines the amount of lines in a file, then returns the answer to the main thread.我正在使用 pthread_create 创建一个线程,该线程检查文件中的行数,然后将答案返回给主线程。 I have tried using pthread_join, and malloc() but I am new to both and must have used them improperly.我曾尝试使用 pthread_join 和 malloc(),但我对这两者都不熟悉,一定是使用不当。 If anyone knows how to pass an integer from a thread back to the main, please help.如果有人知道如何将整数从线程传递回主线程,请帮忙。 My code is below.我的代码如下。

#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);
}

I am running an Ubuntu virtual machine and using Visual Studio Code if that is of any help.如果有任何帮助,我正在运行 Ubuntu 虚拟机并使用 Visual Studio Code。 When I run the code above I get a "Core Dump (Segmentation Fault)" error.当我运行上面的代码时,出现“核心转储(分段错误)”错误。 Again, an help is much appreciated.再次,非常感谢帮助。

You are making everything needlessly complicated.你让一切变得不必要地复杂。 Make a struct such as this:制作一个像这样的结构:

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);

Fill in ret_val before the thread is done.在线程完成之前填写ret_val

I made the struct instance static just in case the calling thread would go out of scope before the count lines thread is done.我将结构实例static ,以防万一调用线程在计数行线程完成之前超出范围。 If it never does that, static isn't necessary.如果它从不这样做,则不需要static

Before you create a thread, check if the file is really opened:在创建线程之前,请检查文件是否真的打开:

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

Also fh is already a pointer.另外 fh 已经是一个指针。 You dont need to pass &fh (pointer to pointer) to thred create (you're expecting FILE* not FILE** in count_lines).不需要将 &fh (指向指针的指针)传递给 thred create(您在 count_lines 中期望 FILE* 而不是 FILE**)。 Also check if thread creation succeeded:还要检查线程创建是否成功:

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

Also check the retval (dereference only if valid pointer, otherwise segmentation error):还要检查 retval(仅当指针有效时才取消引用,否则会出现分段错误):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM