[EMAIL PROTECTED] wrote:
In the unix world using pthreads, when you allocate
thread-local storage, you specify a callback function
to delete the storage when the thread terminates.

Question:  How do you do the same thing on windows?

If you are building a DLL, you can use DllMain(DLL_THREAD_DETACH). Otherwise, your pretty much only option is to keep track of everything you have allocated and to free it all at once during final cleanup. This is a very unfortunate deficiency in Windows TLS APIs.

Note that DLL_THREAD_DETACH might not be reliable. For example, if your DLL has been loaded dynamically with LoadLibrary it won't get DLL_THREAD_ATTACH notifications for every individual thread that's running at the time - it'll get a single DLL_PROCESS_ATTACH. So you should get and set your TLS data lazily - check whether it's there, if it's not the thread is calling you for the first time so allocate the data, otherwise use the data previously stored.

Similarly, when your DLL is explicitly unloaded with FreeLibrary, you won't get DLL_THREAD_DETACH from every thread running at the moment - you'll get a single DLL_PROCESS_DETACH. It is wise to keep an independent list of every piece of TLS data ever allocated and to free it all in DLL_PROCESS_DETACH notification.

Igor Tandetnik

Reply via email to