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) { ...