D-Programming-Language/druntime — pull request #86 by rainers (2011-11-21 07:12:37+00:00)
Title: fix deadlock when creating a thread while executing DllMain in another thread

A recent bug report for Visual D exhibited a problem with the thread creation
inside a DLL: if a thread is created while another thread is just excecuting
DllMain(THREAD_ATTACH), a dead lock is almost inevitable:

Main thread, that creates the new thread executes:

Thread.start()
{
//....
synchronized( slock )
{
-> m_hndl = cast(HANDLE) _beginthreadex( null, m_sz, &thread_entryPoint, cast(void*) this, 0, &m_addr );
add( this );
}
}

While the other thread executes:

DllMain()
{
dll_thread_attach()
{
//....
thread_findByAddr()
{
-> synchronized( Thread.slock )
{
foreach( t; Thread ) ...

The problem is: the OS serializes calls to CreateThread and DllMain, so the
threads hang at the marked lines.

The solution is to create the thread suspended without the slock, and just add and resume it
with the lock acquired.