I used to get a trouble with pthread_exit(). I know there is no way to use pthread_exit() in a way like
pthread_exit(&some_local_variable);
We always need to use pthread_exit() like:
pthread_exit("Thread Exit Message or something necessary information");
I once coded a simple program for testing purpose.
I made four thread functions for addition, subtraction, multiplication and division of two integers, respectively. Then while performing these operations on four different threads, I tried to return the result of the operation by pthread_exit(). What I mean is something like:
pthread_exit(&add_result);
When I ran the code in CentOS 6, I got the desired result (i.e., garbage values from all the threads) as pthread_exit() cannot be used like that. But, I got confused. Because for the first time, I ran that code in Ubuntu 11.10 and got three absolutely correct result(correct result of the operation) from three threads and garbage value from one thread. This confused me because why three threads are giving correct result of operation?
Moreover, I used different sleep times for those threads. I found that the thread having least sleep time gave the garbage value.
As gcc is the compiler for both these operating systems, why one system has bugs like this?
It confuses novice programmers like me. If it is not a bug, can anyone explain it to me why is this happening?
pthread_exitjust takes a pointer to avoid. If you pass the address of a variable local to the thread, sometimes that memory will have been reused for something else. Sometimes it will still be there. There’s no guarantee that after a thread exits, some part of the system will go and make sure that all of the memory it was using is set to garbage values.It’s not a bug – the system is doing exactly what you ask it.
Bonus related answer – Can a local variable’s memory be accessed outside its scope?