标签:
下例示范如何设定DLL,使之支持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 will 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;
}
_declspec(thread)具有线程局部性,对于每一个线程是独一无二的。
例: _declspec(thread) DWORD gProgressCounter;
也可以用到结构体上。即将DWORD换成结构体类型即可。
_declspec(thread)的限制
第一:
第二:
一个DLL如果使用了_decls pec(thread),就没有办法被LoadLibrary()载入。因为线程局部节区的大小计算是在程序启动时完成的,没有办法在一个新的DLL载入时重新计算。
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/wangfengfan1/article/details/47167423