Background I am finishing up upgrading my MFC framework project from prototype to alpha production code. The task was to synchronize its threads. I used a mixture of mutexes, condition variables and binary semaphores. This has been mostly successful. The stackoverflow case that most resembles my question is std::condition_variable wait() and notify_one() synchronization.
Problem Occasionally, though, an atomicity problem occurs after new'ing a certain class derived from CWinThread (RxWs2SocketThread). RxWs2SocketThread switches to the new class'es thread and executes InitInstance and switches back again like it is supposed to. In single-threaded programs, when ResumeThread is called, the thread switch to InitInstance occurs without problem, but in my multithreaded program, I have to control the switching. Here is the code:
The occasional fail occurs between line 95 and 102. Here is the app log showing a successful handoff:
The number to the left is the thread number. Line numbers are in brackets like [100]. Note that [100] is the instrumentation for the actual wait call on line 102. And this app log shows an example of where it fails:
In this log, the notify_one occurs before the wait, which causes the program to hang. Note that line [100] in the app log, which represents the wait call in the code on line [102].
Question This tells me I need to provide atomicity between the ResumeThread and std::condition_variable.wait() calls. How can I do that? I have to resume the class thread, otherwise the InitInstance won't be called, but I can't do a wait after I resume the thread.