For a lightweight signal between threads on Windows, WaitOnAddress
is the ideal tool starting from Windows 8. I have to support Windows 7 for the time being, and the best improvement I found (both searching around and reading MSDN) over a Win32 API Event is to go with SleepConditionVariableCS
.
Here is a minimal example (handle Ctrl-C in a console app):
//HANDLE Signal; // event
CONDITION_VARIABLE Signal;
CRITICAL_SECTION cs;
BOOL WINAPI CtrlHandler(DWORD ctl){
switch (ctl) {
case CTRL_C_EVENT: /*SetEvent(Signal);*/ WakeConditionVariable(&Signal); return TRUE;
default: return FALSE; // pass it to the system
}
}
int main(){
//Signal = CreateEventA(NULL, TRUE /*manual-reset event*/,
// FALSE/*initial nonsignaled*/, "ctrl-c_sig023xgyI8");
InitializeConditionVariable(&Signal); InitializeCriticalSection(&cs);
SetConsoleCtrlHandler(CtrlHandler, TRUE) // register CtrlHandler with the system
// auto hThread = CreateThread(nullptr, 0, worker, nullptr, ..);
//WaitForSingleObject(Signal, INFINITE);
EnterCriticalSection(&cs);
SleepConditionVariableCS (&Signal, &cs, INFINITE);
LeaveCriticalSection(&cs);
// stop thread, cleanup, CloseHandle(hThread); CloseHandle(Signal);
return 0;
}
This example forces the "signal" use-case : the system starts a dedicated thread just to run your CtrlHandler
(when the user enters Ctrl-C) which gets a chance then to signal the main
thread for user-requested stop.
Is there a better (lighter) approach in the Win32 API or C++ (knowing that, of course, C++ has to ultimately go through the Win32 API).