CEvent-like behavior with Boost.Thread

The problem is in the words:

For my application, I have a class that is read from the serial port. It uses Windows primitives to process the COM port and has a stream for asynchronous reading. I am trying to convert this from Windows primitives using Boost libraries like Boost.Asio and Boost.Thread.

In the Windows port, there were several MFC CEvent variables in my I / O stream, each of which represented a message: “Read”, “Request Write”, “Read Complete”, “Write Complete”, “Canceled IO”. They were expected using WaitForMultipleObjects.

The problem is that Boost.Thread seems to have analogies for neither CEvent nor WaitForMultipleObjects. The closest I came is to drop them and replace the events with a set of logic elements, and then use the variable_ condition, which calls its notify_all () function whenever the logical value changes.

However, boost :: condition_variable differs in one critical way from CEvent: if CEvent signaling is signaled while it is not waiting, then the next wait on it immediately completes successfully. With boost :: condition_variable, any notification function is ignored if it does not wait.

This means that there is always a gap between checking flags and waiting for a condition_variable in which a notification may be lost. This causes the thread to hang.

Does anyone know a solution to this problem?

:

// Old IO Thread
CEvent msg_cancel;
CEvent msg_read_req;
CEvent msg_write_req;
CEvent msg_read_comp;
CEvent msg_write_comp;

CEvent events[] = { 
    msg_cancel, 
    msg_read_req, 
    msg_write_req,
    msg_read_comp,
    msg_write_comp
};

bool cancel = false;

while (!cancel)
{
    switch(WaitForMultipleObjects(5, events, false, INFINITE))
    {
        case WAIT_OBJECT_0 :
            // msg_cancel
            cancel = true;
            break;

        ...
     }
}

Boost.Thread?

+3
1

, Windows, condition . , , .

, ( active, ) :

condition-variable
mutex

main-thread:
  lock(mutex) { start condition-signaling-thread }
  while(some predicate) {
    condition-variable.wait(mutex)
    do-stuff
  }

condition-signaling-thread:
  loop:      
    lock(mutex) {
      do-whatever
    }
    condition-variable.notify();

, , , . (. Java notify() , , ++, , , ).

, boost.thread Windows ( posix-semaphores, btw), , . , .

+3

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


All Articles