How to return a value from pthread threads in C?

Petr Peller picture Petr Peller · Feb 12, 2010 · Viewed 122.8k times · Source

I'am new to C and would like to play with threads a bit. I would like to return some value from a thread using pthread_exit()

My code is as follows:

#include <pthread.h>
#include <stdio.h>

void *myThread()
{
   int ret = 42;
   pthread_exit(&ret);
}

int main()
{
   pthread_t tid;
   void *status;

   pthread_create(&tid, NULL, myThread, NULL);
   pthread_join(tid, &status);

   printf("%d\n",*(int*)status);   

   return 0;
}

I would expect the program output "42\n" but it outputs a random number. How can I print the returned value?

EDIT: According to first answers the problem is that I am returning pointer to local variable. What is the best practice of returning/storing variables of multiple threads? A global hash table?

Thanks in advance

Answer

anon picture anon · Feb 12, 2010

You are returning the address of a local variable, which no longer exists when the thread function exits. In any case, why call pthread_exit? why not simply return a value from the thread function?

void *myThread()
{
   return (void *) 42;
}

and then in main:

printf("%d\n",(int)status);   

If you need to return a complicated value such a structure, it's probably easiest to allocate it dynamically via malloc() and return a pointer. Of course, the code that initiated the thread will then be responsible for freeing the memory.