I was wondering about the use of pthread_key_create
while 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've left out a fair amount of detail.
For any thread that isn't the main thread, this is obviously fine (provided locking etc.), and whenever a thread dies, my workoncomplex
function gets called and manipulates the foo
object.
My question is, is this valid for the main thread, as obviously the pthreadkey
's calling of the destructor happens at thread wind down, but is it guaranteed to run before the statics are destructed? If so, would I have to check if I'm in the main thread and just return immediately? Or can I just treat all threads the same and assume my static objects will still be around.
The destructor function is not called on application exit. It is only called when a thread exits.
If you exit the main thread with
pthread_exit()
then the destructor function will be called, but the application is not yet being shut down so it is safe to use thestatic
variables.If you call
exit()
or return frommain()
then the destructor function will not be called, so the fact that thestatic
variables are destroyed is not a problem. Useatexit()
to ensure that your destructor function is called on return frommain()
or on a call ofexit()
.