简体   繁体   中英

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. I have tried using pthread_join, and malloc() but I am new to both and must have used them improperly. 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. 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.

I made the struct instance static just in case the calling thread would go out of scope before the count lines thread is done. If it never does that, static isn't necessary.

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. You dont need to pass &fh (pointer to pointer) to thred create (you're expecting FILE* not FILE** in count_lines). 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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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