Access Violation in WakeAllConditionVariable on DLL Shutdown

I have a situation where I have a workflow in a DLL (node's own module) that it uses std::condition_variablefor synchronization. When the executable exits from it, it just kills my worker threads, and since it has its own node module, I don’t have access to DLLMain, so I don’t know about the upcoming shutdown.

When I try to notify my (killed and therefore non-existent) thread to close with notify_all (), the call simply hangs (in window 7) or crashes (Windows 10).

After some research, I found that RTL uses the internal CONDITION_VARIABLE. I can reproduce the failure with this small piece of code:

#include <Windows.h>
#include <thread>
#include <condition_variable>
#include <chrono>

std::mutex mutex;
std::condition_variable cond;

CONDITION_VARIABLE win_cond = CONDITION_VARIABLE_INIT;
CRITICAL_SECTION cs;

void worker() {
    //std::unique_lock<decltype(mutex)> lock(mutex);
    //cond.wait(lock);

    EnterCriticalSection(&cs);
    SleepConditionVariableCS(&win_cond, &cs, INFINITE);
    LeaveCriticalSection(&cs);
}

int main()
{
    InitializeCriticalSection(&cs);
    std::thread thread(worker);
    std::this_thread::sleep_for(std::chrono::seconds(1));

    // Simulate DLL shutdown with lpReserved != null
    ::TerminateThread(thread.native_handle(), 0);

    //cond.notify_all();
    WakeAllConditionVariable(&win_cond);  // crash

    thread.join();
    return 0;
}

My questions:

  • Is it me or is it a mistake?
  • , /?

, ++, , Windows.

+4

Source: https://habr.com/ru/post/1694942/


All Articles