Thread local storage (TLS) enables multiple threads of the same process to use an index allocated by the TlsAlloc function to store and retrieve a value that is local to the thread. In this example, an index is allocated when the process starts. When each thread starts, it allocates a block of dynamic memory and stores a pointer to this memory in the TLS slot using the TlsSetValue function. The CommonFunc function uses the TlsGetValue function to access the data associated with the index that is local to the calling thread. Before each thread terminates, it releases its dynamic memory. Before the process terminates, it calls TlsFree to release the index.
// TLS.cpp : Defines the entry point for the console application.<br />//</p><p>#include "stdafx.h"<br />#include <Windows.h><br />#include <stdio.h><br />#include <process.h></p><p>//use tls to get time<br />DWORD gtlstime;<br />DWORD InitStartTime();<br />DWORD GetUsrTime();</p><p>UINT __stdcall ThreadFunc(LPVOID)<br />{<br />int i;<br />//initilize time<br />printf("/nThe thread is going to start.Thread id: %-5d, Start time: %d/n", ::GetCurrentThreadId(), InitStartTime());<br /> //InitStartTime();<br />//stimulate to do work<br />i = 10000*10000;<br />while(i--)<br />{</p><p>}</p><p>printf("The thread is going to exit.Thread id: %-5d, Used time: %d/n/n", ::GetCurrentThreadId(), GetUsrTime());<br />return 0;<br />}</p><p>int _tmain(int argc, _TCHAR* argv[])<br />{<br />UINT uid;<br />int i;<br />HANDLE h[10];</p><p>gtlstime = ::TlsAlloc();</p><p>for (i=0; i<10; i++)<br />{<br />//::Sleep(10);<br />h[i] = (HANDLE)::_beginthreadex(NULL, 0, ThreadFunc, NULL, 0, &uid);<br />}</p><p>for (i=0; i<10; i++)<br />{<br />::WaitForSingleObject(h[i], INFINITE);<br />::CloseHandle(h[i]);<br />}</p><p>::TlsFree(gtlstime);<br />getchar();<br />return 0;<br />}</p><p>DWORD InitStartTime()<br />{<br />DWORD dwstart = ::GetTickCount();<br />::TlsSetValue(gtlstime, (LPVOID)dwstart);<br />return dwstart;<br />}</p><p>DWORD GetUsrTime()<br />{<br />DWORD dwend;<br />dwend = ::GetTickCount();<br />dwend = dwend - (DWORD)::TlsGetValue(gtlstime);<br />return dwend;<br />}