Thread Local Storage (TLS) enables multiple threads of the same process to use an index allocated byTlsallocFunction 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 usingTlssetvalueFunction. The commonfunc function usesTlsgetvalueFunction 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 CILSTlsfreeTo 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 ",: 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/>}