线程局部存储(TLS)

来源:互联网 发布:淘宝一分钱虚拟商品 编辑:程序博客网 时间:2024/05/17 20:09

尴尬下例示范如何设定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载入时重新计算。




0 0
原创粉丝点击