How to return a value from pthread threads in C?
Here is a correct solution. In this case tdata is allocated in the main thread, and there is a space for the thread to place its result.
#include <pthread.h>
#include <stdio.h>
typedef struct thread_data {
int a;
int b;
int result;
} thread_data;
void *myThread(void *arg)
{
thread_data *tdata=(thread_data *)arg;
int a=tdata->a;
int b=tdata->b;
int result=a+b;
tdata->result=result;
pthread_exit(NULL);
}
int main()
{
pthread_t tid;
thread_data tdata;
tdata.a=10;
tdata.b=32;
pthread_create(&tid, NULL, myThread, (void *)&tdata);
pthread_join(tid, NULL);
printf("%d + %d = %d\n", tdata.a, tdata.b, tdata.result);
return 0;
}
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.