TLS线程局部存储的使用
// useTLS.cpp : 定义控制台应用程序的入口点。#include "stdafx.h"
#include <Windows.h>
#include <process.h>
//声明
VOID InitStartTime();
DWORD GetUserTime();
//TLS索引,作全局变量
DWORDg_dwTlsIndex;
VOID InitStartTime()
{
DWORD dwStartTime = GetTickCount();
::TlsSetValue(g_dwTlsIndex,(LPVOID)dwStartTime);
}
DWORD GetUserTime()
{
DWORD dwNowTime = GetTickCount();
DWORD dwStartTime = (DWORD)::TlsGetValue(g_dwTlsIndex);
return dwNowTime - dwStartTime;
}
UINT WINAPI ThreadProc(LPVOID lpParameter)
{
//模拟线程的工作过程
DWORD i = 1000 * 1000 *100;
while (i--)
{
}
printf("Thread ID:%-5d,Use Time:%d\n",::GetCurrentThreadId(), GetUserTime());
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread;
//得到TLS索引
g_dwTlsIndex = ::TlsAlloc();
//开启十个线程,计算每个线程运行的时间
for (int i=0;i<10;i++)
{
hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, NULL, 0, NULL);
}
//等待工作线程
::WaitForMultipleObjects(10, hThread, TRUE, INFINITE);
for (int i=0;i<10;i++)
{
//::WaitForSingleObject(hThread, INFINITE);
::CloseHandle(hThread);
}
//释放TLS
::TlsFree(g_dwTlsIndex);
return 0;
}
页:
[1]