首页 > 代码库 > 03UseTls

03UseTls

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<windows.h>
 4 #include<process.h>
 5 
 6 int g_nTlsNum;
 7 UINT __stdcall ThreadProc(LPVOID);
 8 void InitialStartTime();
 9 DWORD GetUsedTime();
10 
11 UINT __stdcall ThreadProc(LPVOID lpParam)
12 {
13     InitialStartTime();
14     int i = 10000*10000;
15     while(i--);
16     printf("The Thread that its id is %d Runing time is %d\n",::GetCurrentThreadId(),GetUsedTime());
17     
18     return 0;
19 }
20 void InitialStartTime()
21 {
22     DWORD dwStartTime = ::GetTickCount();
23     ::TlsSetValue(g_nTlsNum,&dwStartTime);
24 }
25 DWORD GetUsedTime()
26 {
27     return ::GetTickCount() - *((DWORD *)::TlsGetValue(g_nTlsNum));
28 }
29 int main(int argc,char* argv[])
30 {
31     HANDLE h[10];
32     unsigned dwThreadId;
33     g_nTlsNum = ::TlsAlloc();
34     for(int i = 0;i<10;i++)
35     {
36         h[i] = (HANDLE)::_beginthreadex(NULL,0,ThreadProc,NULL,0,&dwThreadId);
37     }
38     ::WaitForMultipleObjects(10,h,true,INFINITE);
39     for(int i = 0;i<10;i++)
40     {
41         ::CloseHandle(h[i]);
42     }
43     ::TlsFree(g_nTlsNum);
44     
45     system("pause");
46     return 0;
47 }

 

03UseTls