Why does Windows 10 start extra threads in my program?
Lets see a simple code,
class AA
{
...
};
AA& getAA(){
static AA aa;
return aa;
}
class BB
{
public: BB() { getAA(); ... }
...
};
thread_local BB bb;
I added more information what I encounterd.
. With this simple code, I rewrite callstacks.
The exception is thrown occasionally at 0x00007FFB0B1272A6(ntdll.dll). Access violation writing location 0x000000024. The members of g_tss_mutex are zero except LockCount, which was 6, and LockSemaphore, which was 0xffffffffffffffff. The function is _Init_thread_lock() and it is calling EnterCriticalSection(&g_tss_mutex); Worker thread ntdll.dll thread throw this exception. call stack was.
ntdll.dll!00007ffb0b1272a6()
ntdll.dll!00007ffb0b13b5f6()
ntdll.dll!00007ffb0b13b440()
_init_thread_lock()
_Init_thread_header(int *pOnce)
getAA()
BB::BB()
`dynamic initializer for 'bb'()
The call stack of the main thread was
_should_initialize_environment()
pre_c_initialization()
ucrtbased.dll!00007ffe9c1a4ab9
__scrt_common_main_seh()
__scrt_common_main()
WinMainCrtStartup()
....
Loader Threads of Windows 10 thread pool try to initialize thread_local bb. But if Loader threads call constructor of bb before the main thread of a process does not call _scrt_initialize_thread_safe_statics_platform_specific() to gerentee static magic. https://learn.microsoft.com/en-us/cpp/build/reference/zc-threadsafeinit-thread-safe-local-static-initialization?view=vs-2019
I met this situation. What can I do to handle this problem.