win32线程局部存储
成一粒 2011-03-28 10:32:14 #include <iostream>
#include <windows.h>
#include <process.h>
using namespace std;
DWORD g_tlsUsedTime;
void InitStartTime();
DWORD GetUsedTime();
UINT _stdcall ThreadFunc(LPVOID)
{
int i;
InitStartTime();
i=10000*10000;
while(i--){}
cout<<"This thread is coming to end.Tread ID:"
<<::GetCurrentThreadId()<<"Used Time :"<<GetUsedTime()<<endl;
return 0;
}
int main(int argc,char *argv[])
{
UINT uId;
int i;
HANDLE h[10];
g_tlsUsedTime=::TlsAlloc();
for(i=0;i<10;i++)
{
h[i]=(HANDLE)::_beginthreadex(NULL,0,ThreadFunc,0,0,&uId);
}
for(i=0;i<10;i++)
{
::WaitForSingleObject(h[i],INFINITE);
::CloseHandle(h[i]);
}
::TlsFree(g_tlsUsedTime);
return 0;
}
void InitStartTime()
{
DWORD dwStart=::GetTickCount();
::TlsSetValue(g_tlsUsedTime,(LPVOID)dwStart);
}
DWORD GetUsedTime()
{
DWORD dwElapsed;
dwElapsed=::GetTickCount();
dwElapsed=dwElapsed-(DWORD)::TlsGetValue(g_tlsUsedTime);
return dwElapsed;
}
在这个程序的线程入口函数中,i的值在每一次线程执行的时候都是从10000*10000开始的么?
如果相等,那么线程的每一次对零界资源的访问为什么总保持了i值的不变?