Is there a way I can have a function called automatically when the thread it's in exits?
Printable View
Is there a way I can have a function called automatically when the thread it's in exits?
Don't the threads themselves "know" when they exit?
--
Mats
There is no function that executes when a thread exits in Windows (at least not using the standard Windows threading API).
There is the option of using a WaitFor/Single,Multiple/Object() to wait for a thread to finish, and I suppose this will actually work for checking if ANY of the threads have been killed/terminated. It probably requires a separate "watcher" thread to handle the watching, and dealing with the consequences of a particular thread dieing.
--
Mats
The best way, I would say is to do it the MFC way.
Make a CThread class that encapsulates a thread. Then make a virtual function for InitThread and ExitThread that are called when a thread begins and ends respectively. The best way is also to overload start/resume/sleep/kill too, so that if even if you kill the thread, it will call ExtThread first and then kill it (or use a flag).
But you have to be careful if you use "ExitThread" from a another thread, if you are also use TLS - since TLS uses the "current thread" [1] for it's data.
[1] Ok, so it's not calling the OS to ask what the current thread is, but rather the OS when it switches from one thread to another, loads FS (I think) with the current threads local storage, so you can offset off that to get your TLS data.
--
Mats
But if CThread knows when a thread exits, then there must be a way to make your own CThread-like class without having to use evil MFC.
You can't "kill" CWinThread instances, as far as I know. In fact this page seems to confirm this:
http://msdn2.microsoft.com/en-us/library/2s21xzfe.aspx
--Quote:
Originally Posted by MSDN
Mats
>> Is there a way I can have a function called automatically when the thread it's in exits?
Why?
gg
MSDN's own TLS example code uses DLL_THREAD_DETACH. Don't know of anything better for doing something when a thread dies.
http://msdn2.microsoft.com/en-us/lib...97(VS.85).aspx
gg