Wednesday, January 10, 2007

Threads Local Storage(TLS)

In a Multithreading environment sometimes it usually needs to store data specific to each threads, This storage system is called thread local storage. Note that this is also taken from the total process address space. So In this page i am going to show some way how this can be done in Microsoft Windows systems..
       Note that this storage space is very limited , and is varies according to the different implementing platforms (ie OS ).  In windows 2000 , Xp (and later) reserved total 1088 indexes per process. Windows 98 and ME reserves total 80 indexes per process and Windows 98 , NT reserved 64 indexes per process.

So what is this index ? it acts like an handle (not really ) .One thread have only one index at a time . Using this we can access the information specific to that thread. So if i am runnning a program in Xp i can create total 1088 indexes for each threads (Not tried  yet ) in that process. Well , How to get this index ? Microsoft provides APIs to get this indexes as well as storing data to TLS . Following are the APIs

 DWORD TlsAlloc(void);
BOOL TlsSetValue( DWORD dwTlsIndex, LPVOID lpTlsValue );
LPVOID TlsGetValue(  DWORD dwTlsIndex);
BOOL TlsFree(  DWORD dwTlsIndex);
Sample usage

DWORD id;
Main()
{

    id =  TlsAllc();
   CreateThread(Thread1);
   CreateThread(Thread2);
   TlsFree(id);
}
Thread1()
{
    p = ( <type *> )  TlsGetValue(id)
    // do as u like
}
Thread2()
{
    p = ( <type *> )  TlsGetValue(id)
    // do as u like
}
Microsoft also proves much simpler usage. That is __declspec(thread) keryword. This keyword can also be attached to a static or ex tern data members... We know  that usually static data is common to all threads. But if attach _declspec(thread) to that member it is allocated to that threads local storage space.
ex : static __declspec(thread) int tlsData;

No comments: