C++ USES usage instances of TLS thread local storage
- 2020-04-02 02:47:49
- OfStack
This article illustrates the use of TLS thread local storage in C++. Share with you for your reference.
Specific methods are as follows:
//Usetls.cpp: defines the entry point for the console application. & have spent < br / >
//
#include "stdafx.h"
#include <Windows.h>
#include <process.h>
//The statement & have spent < br / >
VOID InitStartTime();
DWORD GetUserTime();
//TLS index, global variable & PI; & have spent < br / >
DWORD g_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)
{
//Simulating the working process of a thread & NBSP; < br / >
DWORD i = 1000 * 1000 *100;
while (i--)
{
}
printf("Thread ID:%-5d,Use Time:%dn",::GetCurrentThreadId(), GetUserTime());
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread[10];
//Get the TLS index & NBSP; < br / >
g_dwTlsIndex = ::TlsAlloc();
//Start ten threads and calculate the running time of each thread & NBSP; < br / >
for (int i=0;i<10;i++)
{
hThread[i] = (HANDLE)_beginthreadex(NULL, 0, ThreadProc, NULL, 0, NULL);
}
//Waiting for a worker thread & NBSP; < br / >
::WaitForMultipleObjects(10, hThread, TRUE, INFINITE);
for (int i=0;i<10;i++)
{
//::WaitForSingleObject(hThread[i], INFINITE);
::CloseHandle(hThread[i]);
}
//Release TLS < br / >
::TlsFree(g_dwTlsIndex);
return 0;
}
Hope that the article described in the C++ programming to help you.