For an embedded system interface I am implementing a class that has up to 8 reading modes (only two are illustrated by the code below - FREERUN and BLOCKRUN) for reading the serial port. The simplified ReaderTest() function for this reader looks like:
void CSerialBoost::ReaderTest()
{
while (RUNflag)
switch (RUNstate) {
case FREERUN:
port.async_read_some(asio::buffer(TextIn, SZTXT),
boost::bind(&CSerialBoost::OnReadFree, this, asio::placeholders::error, asio::placeholders::bytes_transferred));
server.reset();
server.run(error); // it calls OnReadBlock() here
break;
case BLOCKRUN:
port.async_read_some(asio::buffer(TextIn, SZTXT),
boost::bind(&CSerialBoost::OnReadBlock, this, asio::placeholders::error, asio::placeholders::bytes_transferred));
server.reset();
server.run(error); // it calls OnReadFree() here
break;
default: break;
}
port.cancel(error); // cancel all IO operations
}
The class CSerialBoost has the following members:
asio::io_service server;
asio::serial_port port;
asio::error_code error;
volatile int RUNstate; // reader mode
volatile int RUNflag; // start/stop flag
There is an unexpected behavior when I switch from one mode to the other. Assuming there is no incoming data and the code runs in FREERUN, in order to switch to BLOCKRUN, from another thread I do:
RUNstate = BLOCKRUN;
server.stop(); // unblock the event loop
The operation switches to BLOCKRUN, as it should, and when it reaches the server.run(error) line under the BLOCKRUN case it calls the CSerialBoost::OnReadFree() function with the error operation_aborted. The same happens when it switches back to FREERUN - it calls CSerialBoost::OnReadBlock() when it reaches server.run(error) under the FREERUN case.
This is very misleading, since it it always calls the function for the other mode. When I stop/cancel the IO service I expect each case to call its own function (or nothing). Am I expecting too much, or this is normal operation? Am I doing something wrong? Please give a hint on how can I handle this problem. (I'm using boost:asio 1-5-3 under Win XP and Win 7, Visual Studio 2010, and I'm new to boost)
Thank you, MA.