The following example demonstrates how to set a DLL to support TLS.
#include <Windows.h>
This is the shared slot
Static DWORD Gdwtlsslot;
BOOL DllMain (hinstance hinst, DWORD fdwreason, LPVOID lpreserved)
{
LPVOID lpdata;
Unreferenced_parameter (hinst);
Unreferenced_parameter (lpreserved);
Switch (Fdwreason)
{
Case Dll_process_attach:
Find the index that'll be global for all threads
Gdwtlsslot = TlsAlloc ();
if (Gdwtlsslot = = 0xFFFFFFFF)
return FALSE;
Fall through to handle thread attach too
Case Dll_thread_attach:
Initialize the TLS index for this thread.
lpdata = (LPVOID) LocalAlloc (lptr, sizeof (struct ourdata));
if (lpdata! = NULL)
if (TlsSetValue (Gdwtlsslot, lpdata) = = FALSE)
;//this should be handled
Break
Case Dll_thread_detach:
Release the allocated memory for this thread.
lpdata = TlsGetValue (Gdwtlsslot);
if (lpdata! = NULL)
LocalFree ((hlocal) lpdata);
Break
Case Dll_process_detach:
Release the allocated memory for this thread.
lpdata = TlsGetValue (Gdwtlsslot);
if (lpdata! = NULL)
LocalFree ((hlocal) lpdata);
Give back the TLS slot
TlsFree (Gdwtlsslot);
Break
Default
Break
}
return TRUE;
}
the _declspec (thread) has thread locality, is unique for each thread.
Example: _declspec (thread) DWORD gprogresscounter;
can also be used on the structure of the body. To change the DWORD to struct type.
Limitations of _DECLSPEC (thread)
First:
Second:
A DLL If you use the _decls pec (thread), there is no way to be loaded by LoadLibrary (). Because the size calculation of a thread's local section is done at program startup, there is no way to recalculate a new DLL when it is loaded.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Thread-local Storage (TLS)