Quillion Quillion - 11 days ago 4x
C Question

pthread_exit issues returning struct

I have a struct

typedef struct something_t {
int a;
int b;

In my thread function I do

VALUES values;
values.a = 10;
values.b = 11;


And I try to receive by doing

VALUES values;
pthread_join(thread, (void*)&values);
printf("A: %d\B: %d\n", values.a, values.b);

The values I receive are weird every time.
I am confused about how to receive the values that I end up creating in the thread. I am trying to learn threads in C and seems like I have grasped it, but I can't return values. Is there a way? Thanks to anyone for their help.


You are trying to return a stack (local) variable.

This is not allowed, and will not work, since the stack of the thread will be deleted (or at least be invalid) when the thread exits.

To fix this:

VALUES *values = malloc(sizeof VALUES);
values->a = 1;
values->b = 2;
pthread_exit( values );

And then, when you join free the values

VALUES *res;
pthread_join( thread, &res );