The order of destruction of the main thread and the use of pthread_key_create

I was wondering about using pthread_key_create when passing in a destructor function.

I wanted to have something like this:

 static ComplexObject foo; void workoncomplex(void *) { foo.dosomestuff(); } static pthread_key_t pthreadkey; void function_called_by_threads() { pthread_key_create(&pthreadkey, workoncomplex) } 

Obviously, I left a lot of details.

For any thread that is not the main thread, this is obviously excellent (locking is provided, etc.), and whenever the thread dies, my workoncomplex function workoncomplex called and controls the foo object.

My question is whether this is valid for the main thread, since it is obvious that the pthreadkey destructor is called when the thread winds down, but is it guaranteed to be executed before the statics break? If so, should I check if I am included in the main thread and return immediately? Or, I can simply handle all threads the same way and assume that my static objects will still be around.

+4
source share
1 answer

The destructor function is not called when the application exits. It is called only when the stream exits.

If you exit the main thread using pthread_exit() , then the destructor function is called, but the application is not yet closed, so it is safe to use static variables.

If you call exit() or return from main() , then the destructor function will not be called, so the problem that static variables are destroyed is not a problem. Use atexit() to ensure that your destructor function is called when returning from main() or when calling exit() .

+2
source

All Articles