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?
It seems to be a problem that I am returning a pointer to a local variable. What is the best practice of returning/storing variables of multiple threads? A global hash table?
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?and then in main:
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.