basically, I am trying to understand the real purpose of pthread_exit. As you can see, there are multiple pthread_exit code I have tried. And Following are the result i observe :
- Exit 1: 42
- Exit 2: 42
- Exit 3: thread failed
- Exit 4: error
- Exit 5: 42
- Without a pthread_exit statement: 42
Anyways the value passed(10) to pthread_exit is ignored(Exit 2) and prints the value which we modified via the pointer(42). So what is the real purpose of argument of pthread_exit here? confusing.
int a;
void *myThread(void *result)
{
int a = 5;
*((int*)result) = 42;
pthread_exit(result); // Exit 1
//pthread_exit((void *)10); // Exit 2
//pthread_exit(0); // Exit 3
//pthread_exit(); // Exit 4
//pthread_exit((void *)&a); // Exit 5
}
int main()
{
pthread_t tid;
void *status = 0;
int result;
pthread_create(&tid, NULL, myThread, &result);
pthread_join(tid, &status);
if (status != 0 ) {
printf("%d\n",result);
} else {
printf("thread failed\n");
}
return 0;
}
pthread_exit()
takes the pointer value you pass it and arranges for the pointer value to be returned into the void *
variable whose address is passed to pthread_join()
.
In your case, this means that the value passed to pthread_exit()
will end up in the status
variable in main()
. You never print the contents of status
- all you do is test it against NULL
in the if ()
condition. The value you are printing is the value stored in result
, which is not modified by the pthread_exit()
or pthread_join()
, so of course it will always be the same.
In your my_thread()
function, the pointer result
is always going to be the address of the result
variable in main()
, so these are the cases you will see:
pthread_exit(result); // Exit 1
In main()
, status
will end up equal to (void *)&result
, which is necessarily non-NULL, so the test succeeds. It then prints the value of result
, which was set to 42
by the first line of my_thread()
.
pthread_exit((void *)10); // Exit 2
In main()
, status
will end up equal to (void *)10
. On any common implementation of C, this value will compare unequal to NULL
, so the test succeeds. It then prints the value of result
, which was set to 42
by the first line of my_thread()
.
pthread_exit(0); // Exit 3
In main()
, status
will end up equal to (void *)0
. This necessarily compares equal to NULL
, so the test fails. It then prints "thread failed".
If you print the value of the status
pointer with:
printf("status = %p\n", status);
before the if()
, you will be able to see how the value passed to pthread_exit()
is returned.