The example in this article describes the use of C + + thread local storage. Share to everyone for your reference.
The specific methods are as follows:
Copy Code code as follows:
UseTLS.cpp: Defines the entry point for a console application.
//
#include "stdafx.h"
#include <Windows.h>
#include <process.h>
Statement
VOID Initstarttime ();
DWORD Getusertime ();
TLS index, as global variable
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)
{
To simulate a thread's working process
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[10];
Get TLS index
G_dwtlsindex =:: TlsAlloc ();
Turn on 10 threads to calculate when each thread is running
for (int i=0;i<10;i++)
{
Hthread[i] = (HANDLE) _beginthreadex (null, 0, threadproc, NULL, 0, NULL);
}
Waiting for worker threads
:: WaitForMultipleObjects (Ten, Hthread, TRUE, INFINITE);
for (int i=0;i<10;i++)
{
:: WaitForSingleObject (Hthread[i], INFINITE);
:: CloseHandle (Hthread[i]);
}
Releasing TLS
:: TlsFree (G_dwtlsindex);
return 0;
}
I hope this article will help you with the C + + program design.