TLS in a static library
-
All the documentation on thread local storage is about using it in a DLL. I want to use it in a static library. Are there any issues?
-
All the documentation on thread local storage is about using it in a DLL. I want to use it in a static library. Are there any issues?
DWORD g_dwThreadIndex = 0; TCHAR *g_szFixedBuf = 0; TCHAR *function() { if (g_dwThreadIndex == 0) { g_dwThreadIndex = TlsAlloc(); } if (g_szFixedBuf == 0) { g_szFixedBuf = new TCHAR[1024]; } // Do some thread specific work and put it in g_szFixedBuf return g_szFixedBuf; } There are obviously two problems: g_szFixedBuf is initialized once per process and not per thread. I can use a an array of pointers, one for each thread. But since the number of threads is unknown, not sure how long the array should be. The second problem is freeing the memory. Any ideas how this can be addressed?
-
DWORD g_dwThreadIndex = 0; TCHAR *g_szFixedBuf = 0; TCHAR *function() { if (g_dwThreadIndex == 0) { g_dwThreadIndex = TlsAlloc(); } if (g_szFixedBuf == 0) { g_szFixedBuf = new TCHAR[1024]; } // Do some thread specific work and put it in g_szFixedBuf return g_szFixedBuf; } There are obviously two problems: g_szFixedBuf is initialized once per process and not per thread. I can use a an array of pointers, one for each thread. But since the number of threads is unknown, not sure how long the array should be. The second problem is freeing the memory. Any ideas how this can be addressed?
Why not make a Thread class where you put the Tls functionality. And if all your threads is started from that class you shouldnt have any problem destroying the Tls when the Thread object is destroyed. Never do global stuff... it really hurts the design. Magnus