Home > front end >  how to wait thread created in DLLmain finish?
how to wait thread created in DLLmain finish?

Time:06-30

I create a new thread in Dllmain by CreateThread api, which does not involve Thread synchronization, it is only a separate thread. And the Dllmain invokes WaitForSingleObject(funcThread, INFINITE); to force the main thread to wait for funcThread to finish. Then I dynamic link this Dllmain, but the result shows the funcThread finish early. I know adding a System Pause will work, but do you have some ways to make it work with only changing dllmain file.

main.exe

#include <Windows.h>
#include <iostream>

int main() {
    HINSTANCE hModule = LoadLibrary(L"Dllmain.dll");
    return 0;
}

Dllmain.dll

#include <Windows.h>
#include <iostream>

DWORD WINAPI function(LPVOID lpParam) {
    for (int i = 0; i < 100; i  ) {
        printf("%d \n", i);
    }

    return 0;
}
HANDLE funcThread;

BOOL APIENTRY DllMain(HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved
) {
    switch (ul_reason_for_call) {
    case DLL_PROCESS_ATTACH:
        funcThread = CreateThread(
            NULL,                   // default security attributes
            0,                      // use default stack size  
            function,       // thread function name
            NULL,          // argument to thread function 
            0,                      // use default creation flags 
            NULL);
        printf("attach process!\n");
        break;
    case DLL_PROCESS_DETACH:
        printf("detach process!\n");
        WaitForSingleObject(funcThread, INFINITE);

        break;
    case DLL_THREAD_ATTACH:
        printf("attach thread!\n");
        break;

    case DLL_THREAD_DETACH:
        printf("detach thread!\n");
        break;
    }
    return TRUE;
}

output: enter image description here

it should also print 23 to 99 and detach process messages, but all of them miss.

CodePudding user response:

What you are trying to do is explicitly NOT supported from DllMain.

From : https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices?redirectedfrom=MSDN

You should never perform the following tasks from within DllMain:

  • Synchronize with other threads. This can cause a deadlock.
  • Call ExitThread. Exiting a thread during DLL detach can cause the loader lock to be acquired again, causing a deadlock or a crash.
  • Call CreateThread. Creating a thread can work if you do not synchronize with other threads, but it is risky.

And more.

CodePudding user response:

The problem here is fundamental. You can't create a thread from DLL_PROCESS_ATTACH. It's running under loader lock.

  • Related