Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notification when a thread is destroyed [duplicate]

Is there a way to get a notification that a thread no longer runs (has returned) in your application?
I know this is possible in kernel mode (using PsSetCreateThreadNotifyRoutine), but is there a way to know this from user mode, using only Win32 API ?

The problem is that I can't control the code in the thread, because my module is part of a library. Making a driver to monitor the system would not be too hard, but it's annoying for the users to install a driver even for a basic application that uses my library.

My code uses TLS storage, and under Linux/Unix pthread_key_create can take a pointer to a function that is called when the thread is destroyed. But TlsAlloc (Windows) has nothing like this...

Thanks in advance!

like image 659
Gratian Lup Avatar asked Dec 09 '22 19:12

Gratian Lup


2 Answers

Depends on what kind of libraray you have. For a DLL could handle the thread termination in your DllMain (DLL_THREAD_DETACH). The MSDN states that this is the best place to deal with TLS Resources.

Keep in mind that this callback is only calld for a thread exiting cleanly (not by e.g TerminateThread()).

like image 125
Frank Bollack Avatar answered Dec 25 '22 14:12

Frank Bollack


Similar functionality is available with Fibers. From MSDN:

FlsAlloc, FlsCallback, FlsFree

FlsCallback Callback Function

An application-defined function. If the FLS slot is in use, FlsCallback is called on fiber deletion, thread exit, and when an FLS index is freed.

like image 39
Indy9000 Avatar answered Dec 25 '22 12:12

Indy9000