c++dllshared-librariesc++20thread-local-storage

Using thread-local storage variables INTERNALLY in a DLL


I am working on a project where I need to use thread-local storage (TLS) variables within a DLL, but I do not intend to export these symbols outside of the DLL.

To the best of my knowledge, thread_local variables cannot be exported to a DLL, at least not in MSVC. My question is whether it is feasible and safe to use thread-local storage variables internally within a DLL without exporting them as symbols.


Solution

  • Thread local variables can be used in a DLL if it uses load-time binding (that is, linking to the .lib stub). This has nothing to do with whether the variable is exported or not. However, if it the DLL is loaded via LoadLibrary then you must use the TLS API (TLSAlloc etc), at least so long as any library function that uses these thread-local variables will be called on a thread that already exists at the time of the load.

    This is because the region for TLS variables for each thread is allocated at the time the thread is created, and if a new dLL is loaded that region does not grow to match the needs of the new DLL.