std::thread cause deadlock in DLLMain

前端 未结 4 975
无人共我
无人共我 2020-12-28 11:14

So, this is what I\'m talking about: std is complex.

In VS2013 this simple program will cause a deadlock.

#include 
#include 

        
4条回答
  •  执笔经年
    2020-12-28 11:19

    The specification for std::thread contains the following requirement (N4527 §30.3.1.2[thread.thread.constr]/6):

    Synchronization: The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.

    (where f is the callable entity which is to be executed on the newly created thread.)

    The constructor for the std::thread cannot return until the new thread starts executing the thread procedure. When a new thread is created, before the thread procedure is invoked, the entry point of each loaded DLL is invoked for DLL_THREAD_ATTACH. To do this, the new thread must acquire the loader lock. Unfortunately, your existing thread already holds the loader lock.

    Thus, you deadlock: the existing thread cannot release the loader lock until the new thread starts executing the thread procedure but the new thread cannot execute the thread procedure until it can acquire the loader lock, which is held by the existing thread.

    Note that the documentation expressly recommends against creation of threads from the DLL entry point:

    You should never perform the following tasks from within DllMain: [...] Call CreateThread. Creating a thread can work if you do not synchronize with other threads, but it is risky.

    (That page has a long list of things that should not be done from a DLL entry point; this is just one of them.)

提交回复
热议问题