views:

228

answers:

4

Hi!
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!

+4  A: 

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.

Indeera
Now I saw that this doesn't work under Win Xp, only 2003 and Vista :(
lgratian
A: 

You can simply call WaitForSingleObject on the thread handle.

On Freund
+2  A: 

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: http://stackoverflow.com/questions/91935/windows-api-spying-hijacking-techniques for some details on this kind of hooking...

Len Holgate
note to self, should have asked if the 'library' was a dll...
Len Holgate
+5  A: 

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

Frank Bollack
Yes, it's a DLL. This seems to fit best in my case.
lgratian