Calling a function when thread is exiting in PThreads or Windows Calling a function when thread is exiting in PThreads or Windows windows windows

Calling a function when thread is exiting in PThreads or Windows


So after a few code reviews, we were able to find a much more elegant way to do this in Linux, which matches both what Windows does with Fibers (as Neeraj points out) as well as what I expected to find when I started looking into this issue.

The key is that pthread_key_create takes in, as the second argument, a pointer to a destructor, which is called when any thread which has initialized this TLS data dies. I was already using TLS elsewhere per thread, but a simple store into TLS would get you this feature as well to ensure it was called.


Change this:

pthread_create(&ntid, NULL, threadFunc, &nVal);

into:

struct exitInformData{   void* (CB*)(void*);   void* data;   exitInformData(void* (cp*)(void*), void* dp): CB(cp) data(dp) {}};pthread_create(&ntid, NULL, exitInform, new exitInformData(&threadFunc, &nVal));

Then Add:

void* exitInform(void* data){    exitInformData* ei = reinterpret_cast<exitInformData*>(data);    void* r = (ei.CB)(ei.data);   // Calls the function you want.    callMeOnExit();               // Calls the exit notification.    delete ei;    return r;}


For Windows, you could try Fls Callbacks. They FLS system can be used to allocate per thread (ignore the 'fiber' part, each thread contains one fiber) storage. You get this callback to free the storage, but can do other things in the callback as well.