问题
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.
回答1:
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);
回答2:
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
.
回答3:
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);
回答4:
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.
来源:https://stackoverflow.com/questions/12887214/pthread-exit-issues-returning-struct