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);

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);



Popular posts from this blog

Clearcase check in/uncheck out all the checked out files script


Duplicating a local copy of project from TFS and making web software client factory to work