In WinAPI you can create and access thread local storage using functions such as TlsAlloc, TlsGetValue, TlsSetValue and TlsFree. The API supposes that you will store pointers in the thread local storage (for sure you can store size_t integers casted to pointers, but often we would like to store more information). So, probably this memory will be allocated by every thread which uses this data. But the problem is how to free this memory at thread exit.
In pthreads you have an optional destructor argument for pthread_key_create function (pthreads version of TlsAlloc). But in raw WinAPI TlsAlloc doesn't provide such option. How to implement a custom destructor for thread local storage using only WinAPI and plain C (so no modern C++ thread local storage which supports object destructors on the compiler level)?
I'm writing a normal program, not a DLL, so I don't care about the corner case "DLL unloaded before program exit, so the destructor code became unavailable". I think, I am looking for a function similiar to atexit, but on thread level.
FlsAlloc()callback is called at thread exit. See Fibers aren’t useful for much any more; there’s just one corner of it that remains useful for a reason unrelated to fibers