Split thread access variables after main thread exits
What happens in a multithreaded C ++ program if a dedicated thread accesses shared variables (such as a global variable) after the call thread exits and destroys the shared variable?
class A {
public:
A() { printf("Constructing A\n"); }
~A() { printf("Destructing A\n"); }
void printSomething() { printf("A is printing\n"); }
}
A a;
void thread_func() {
printf("begin thread.\n");
sleep(3); // make sure main thread exit first
a.printSomething();
printf("ending thread");
}
int main(int argc, char** argv) {
std::thread t(thread_func);
t.detach();
return 0;
}
The program produces:
bash$ ./a.out
Constructing A
Destructing A
bash$
It seems that the main thread created a global variable a and destroyed it on exit. Then, what happens after 3 seconds if a detached child thread tries to access this global variable?
And one more confusion: why does the main thread clean up all resources when it exits? It looks like the lifetime of a global variable only depends on the main thread?
source to share
Processes exit when returns main()
, or any thread calls exit()
or _exit()
.
However, it main()
can pthread_exit()
- and this will not complete the process. On Linux, the pthread_exit()
man page :
When the thread ends, the resources shared by the processes (such as mutexes, state variables, semaphores, and file descriptors) are not and functions registered using atexit (3) are not called.
After the last thread in the process exits, the process exits by calling exit (3) with a zero exit status; This frees process resources and registers functions using atexit (3).
source to share