TLS (Thread Local Storage) sample code

This will spawn multiple threads and each thread will access itTLS, including the main thread itself will access its own TLS.

The code will not deallocate the memory in the heap which initially allocated in the thread. The reason is to able to show the content of the TLS and each TLS is localized to each thread.






#include <stdio.h>
#include <Windows.h>
#include <process.h>


static DWORD dwTlsIndex; // address of shared memory

void func(LPVOID);



int main(int argc, char* argv[])
{

if ((dwTlsIndex = TlsAlloc()) == 0xFFFFFFFF)
return FALSE;

//main thread
LPSTR lpszTemp = new char[10];
strcpy(lpszTemp, "main thread");
TlsSetValue(dwTlsIndex, (LPVOID)lpszTemp);


for(int k = 0; k < 10; k++)
{
_beginthread(func, 0, NULL);
}


LPCTSTR pCheck = (LPCTSTR)TlsGetValue(dwTlsIndex);
printf("Main: %s\n", pCheck);
TlsFree(dwTlsIndex);

return 0;

}

void func(LPVOID)
{
char *lpszData;
lpszData = new char[10];

sprintf(lpszData, "%d", GetCurrentThreadId());

LPCSTR lpcszCheck = (LPCTSTR)TlsGetValue(dwTlsIndex);


printf("Prev: %s\n", lpcszCheck);


TlsSetValue(dwTlsIndex, (LPVOID)lpszData);


lpcszCheck = (LPCTSTR)TlsGetValue(dwTlsIndex);
printf("Current: %s\n", lpcszCheck);

}

Comments

Popular posts from this blog

Outlook : "operation failed, object could not be found. " when trying to close a PST.

Troubleshooting Outlook Express (IMAP, POP3, HTTP, NEWS) with the log file

MSSQL GROUP_CONCAT