1

I have a struct

typedef struct something_t {
    int a;
    int b;
} VALUES;

In my thread function I do

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

pthread_exit((void*)&values);

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.

Quillion
  • 6,346
  • 11
  • 60
  • 97

4 Answers4

6

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 );
...
free(res);
perh
  • 1,668
  • 11
  • 14
  • Amazing! Thanks so much, I didn't realize that the stack would be dumped at the end of each new thread, I did notice however that a new memory got allocated for everything but global variables in each thread. – Quillion Oct 14 '12 at 22:58
1

Look's like you are creating a stack object on the thread function and using that in pthread_exit. That struct goes out of scope when the thread function exits and you would be left with garbage.

You are not using the values struct you passed into pthread_join.

Science_Fiction
  • 3,403
  • 23
  • 27
1

Your application has an undefined behavior, as you declared the struct on the stack (and the stack of an exited thread)

Use malloc instead:

VALUES *values = malloc(sizeof(VALUES);
values->a = 10;
values->b = 11;

pthread_exit(values);
MByD
  • 135,866
  • 28
  • 264
  • 277
1

Adding to perh's answer : Use pointer typecasting where it is necessary.

thread function:

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

calling function:

VALUES *res;
pthread_join( thread_id, (void*)&res );
...
free(res);

This is safe and it won't generate warnings on compilation.

Community
  • 1
  • 1
Chaitanya Patel
  • 390
  • 1
  • 4
  • 15