Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please look at code snippet below // these code blocks defined under single .cpp unit in DLL project
------------------ DLL -------------------------

C++
static std::thread sendMessageThread; // define as local static to cpp
//....//
bool  callFunction()
{
   /// Some simple code without spawning any thread or fibers
 }
void WINAPI OnEngineStart()
{
    sendMessageThread = std::thread(callFunction);
};

    BOOL WINAPI DllMain(HINSTANCE hDll, DWORD fdwReason, LPVOID lpvReserved)
    {
        switch (fdwReason)
        {
        case DLL_PROCESS_ATTACH:
            break;
        case DLL_PROCESS_DETACH:
            if (sendMessageThread.joinable())
            {
                sendMessageThread.join(); // is this safe?
            }
            break;
        case DLL_THREAD_ATTACH:
            break;
        case DLL_THREAD_DETACH:
            break;
        }

    return TRUE;
};


------------------------------------- DLL --------------------------

If the process which loaded the DLL call OnEngineStart function then whenever it unloads the DLL(using FreeLibrary WinAPI function), will it wait until sendMessageThread gets finished? and continue with DLL unload procedure?

What I have tried:

I run the program with this DLL,program never crash and halt.But I found these stuff:
Does creating a thread from DllMain deadlock or doesn’t it? – The Old New Thing[^]
Dynamic-Link Library Best Practices (Windows)[^]
Posted
Updated 29-Sep-17 2:06am

1 solution

No, you are doing exactly what Raymond Chen describes in his blog entry. You are waiting for the thread in your DLL_PROCESS_DETACH. Make sure that you understand what 'DLL notifications are serialized' means.

I think I know a way to demonstrate why this is a bad idea... add some code in your sendMessageThread that calls getenv_s, _wgetenv_s[^]. Also add some code to your parent process to load/unload the DLL periodically. This should eventually cause your code to deadlock. The reason for the deadlock is that the CRT accesses a global _ENV_LOCK and will potentially cause a race condition. There are dozens of other scenarios that will cause a deadlock.

One possible solution is to change your architecture by adding a OnEngineStop thread message and do your waiting there.

Best Wishes,
-David Delaune
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900