主线程为线程局部存储分配索引DWORD TlsAlloc(void);
释放 TlsFree(DWORD dwTlsIndex);
调用TlsSetValue和TlsGetValue设置和读取线程数组中的值
BOOL TlsSetValue(DWORD dwTlsIndex , LPVOID lpTlsValue)
LPVOID TlsGetValue(DWORD dwTlsIndex);
#include <windows.h>
#include <stdio.h>
#include <process.h>
DWORD g_tlsUsedTime;
void InitStartTime(){
DWORD dwStart = GetTickCount();
TlsSetValue(g_tlsUsedTime,(LPVOID)dwStart);
}
DWORD GetUsedTime(){
DWORD dwElapsed = GetTickCount();
dwElapsed = dwElapsed - (DWORD)TlsGetValue(g_tlsUsedTime);
return dwElapsed;
}
UINT WINAPI ThreadProc(LPVOID){
int i;
InitStartTime();
i = 10000 * 10000;
while (i--)
{
}
printf("ThreadId = %u\tElapsedTime = %u\n",GetCurrentThreadId(),
GetUsedTime());
return 0;
}
void InitTlsAlloc(){
g_tlsUsedTime = TlsAlloc();
}
int _cdecl main(int argc,char* argv[])
{
UINT uid;
int i;
HANDLE h[10];
InitTlsAlloc();
for(i = 0;i < 10; i++)
{
h[i] = (HANDLE)_beginthreadex(NULL,0,ThreadProc,NULL,0,&uid);
}
for (i = 0; i < 10; i++)
{
WaitForSingleObject(h[i],INFINITE);
CloseHandle(h[i]);
}
TlsFree(g_tlsUsedTime);
return 0;
}