5

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!

1

4 Answers 4

5

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()).

1
  • Yes, it's a DLL. This seems to fit best in my case. Commented Oct 3, 2009 at 9:18
5

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.

1
  • 2
    Now I saw that this doesn't work under Win Xp, only 2003 and Vista :( Commented Oct 3, 2009 at 7:50
2

You can simply call WaitForSingleObject on the thread handle.

2

You could try installing an IAT patching API hook on ExitThread()...

The advantage of this is that you'd get to run in the context of the thread that is exiting which may or may not be useful to you.

See this posting: Windows API spying/hijacking techniques for some details on this kind of hooking...

1
  • 1
    note to self, should have asked if the 'library' was a dll... Commented Oct 3, 2009 at 22:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.