std::thread::join() hangs if called after main() exits when using VS2012 RC

Tracing through Fraser’s sample code in his connect bug (https://connect.microsoft.com/VisualStudio/feedback/details/747145)
with VS2012 RTM seems to show a fairly straightforward case of deadlocking. This likely isn’t specific to std::thread – likely _beginthreadex suffers the same fate.

What I see in the debugger is the following:

On the main thread, the main() function has completed, the process cleanup code has acquired a critical section called _EXIT_LOCK1, called the destructor of ThreadTest, and is waiting (indefinitely) on the second thread to exit (via the call to join()).

The second thread’s anonymous function completed and is in the thread cleanup code waiting to acquire the _EXIT_LOCK1 critical section. Unfortunately, due to the timing of things (whereby the second thread’s anonymous function’s lifetime exceeds that of the main() function) the main thread already owns that critical section.

DEADLOCK.

Anything that extends the lifetime of main() such that the second thread can acquire _EXIT_LOCK1 before the main thread avoids the deadlock situation. That’s why the uncommenting the sleep in main() results in a clean shutdown.

Alternatively if you remove the static keyword from the ThreadTest local variable, the destructor call is moved up to the end of the main() function (instead of in the process cleanup code) which then blocks until the second thread has exited – avoiding the deadlock situation.

Or you could add a function to ThreadTest that calls join() and call that function at the end of main() – again avoiding the deadlock situation.

Leave a Comment