2

This happens with the MSVC 2013 compiler. I have a solution with 2 projects: .exe and .dll.
The .exe source code:

extern "C" int test_dll();

int main() {
    test_dll();

    return 0;
}

The .dll source code:

#include <mutex>

struct AAAA {
    AAAA() {
        std::mutex mutex;
        if (mutex.try_lock()) { // always blocks
            mutex.unlock();
        }
    };

} globalObject;

extern "C" __declspec(dllexport)
int  test_dll() {
    return true;
}

The try_lock call never returns. Here's the call stack:

msvcr120d.dll!Concurrency::details::ThreadScheduler::Create(const Concurrency::SchedulerPolicy & policy) Line 34
msvcr120d.dll!Concurrency::details::SchedulerBase::CreateWithoutInitializing(const Concurrency::SchedulerPolicy & policy) Line 285
msvcr120d.dll!Concurrency::details::SchedulerBase::GetDefaultScheduler() Line 654
msvcr120d.dll!Concurrency::details::SchedulerBase::CreateContextFromDefaultScheduler() Line 571
msvcr120d.dll!Concurrency::details::SchedulerBase::CurrentContext() Line 399
msvcr120d.dll!Concurrency::details::LockQueueNode::LockQueueNode(unsigned int timeout) Line 619
msvcr120d.dll!Concurrency::critical_section::try_lock() Line 1049
msvcp120d.dll!mtx_do_lock(_Mtx_internal_imp_t * * mtx, const xtime * target) Line 75
msvcp120d.dll!_Mtx_trylock(_Mtx_internal_imp_t * * mtx) Line 162
MutexDll.dll!std::_Mtx_trylockX(_Mtx_internal_imp_t * * _Mtx) Line 73
MutexDll.dll!std::_Mutex_base::try_lock() Line 46
MutexDll.dll!AAAA::AAAA() Line 8
MutexDll.dll!`dynamic initializer for 'AAA''() Line 21
[External Code]

This doesn't happen if the global object is created in the main .exe project. Only when in the DLL. What's going on here?

The hang doesn't occur with the MSVC2015 compiler (v140 toolset).

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
  • There are limitations on what you can do in DLL initialisation in windows - e.g. any attempt to start a thread or load another DLL will deadlock. And statics are initialised as part of DLL initialisation. – Alan Stokes Jan 31 '16 at 11:03
  • @AlanStokes: interesting! Got a proof link? – Violet Giraffe Jan 31 '16 at 11:05
  • Start here: https://msdn.microsoft.com/en-us/library/windows/desktop/dn633971(v=vs.85).aspx. That doesn't mention that C++ initialisation happens from DllMain but that's easy to verify from stack traces etc. – Alan Stokes Jan 31 '16 at 12:11

0 Answers0