Why does this C++ static singleton never stop?
I've traced it down to void __cdecl _lock(int locknum)
inside mlock.c
. When main()
ends, the main thread goes there and enters critical section EnterCriticalSection( _locktable[locknum].lock );
. Then Singleton destructor gets called and the other thread tries to enter the same critical section, but can't, and so it starts waiting for main thread to leave the critical section. Main thread, in turn, waits for the other thread. So I guess it's a bug.
On the main thread, after main()
terminates, the CRT acquires the exit lock and calls your static instance destructor, which waits for your background thread to exit.
On the background thread, after your thread function terminates, the CRT attempts to acquire the exit lock to do some thread termination work. This blocks forever because the exit lock is held by the main thread, which is waiting for this thread to exit.
It's a simple deadlock that's caused by the CRT implementation. The bottom line is that you can't await thread termination in a static instance destructor on Windows.