Destruction order of the main thread and the use of pthread_key_create

1.7k views Asked by At

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.

1

There are 1 answers

2
Anthony Williams On BEST ANSWER

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 the static variables.

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