Unlock synchronous read in boost :: asio :: serial_port

I have a boost::thread that does synchronous reads on boost::asio::serial_port . When I destroy an instance of a class that contains both, I want the thread to end gracefully, even if it is blocked while reading. How can i do this?

Looking at the docs , I tried cancel , but it only works for asynchronous read / write. Then I tried close , but I have an exception, and it was not the kind from which you can recover. Perhaps using send_break or native_handle ? (this is Windows and portability is not critical)

Update : I also tried stop io_service pass to the serial port object constructor, but read not unlocked.

Change The exception is actually "exciting", but I would not want to put a try / catch block inside the destructor, and refactoring the code to perform the shutdown process outside the destructor would cause many changes in the upper layers. Therefore, I would only go for this decision if some Boost authority says that there is no other way.

+7
source share
2 answers

It is not possible to unlock synchronous reading as you ask.

There are two options:

  • close / shutdown port and catch the exception that was raised
  • use asynchronous reads and cancel them at application shutdown

The first, of course, is not a good idea, because you cannot distinguish the final application from the error.

+5
source

When you close, you say that you are getting an exception due to which you cannot recover.

What does it mean?

The solution is like catching an exception. Why can't you do this?

In the case when you want to distinguish between error and program termination, check the box when the program terminates before closing. In the catch handler, check the flag. If set, treat it as program termination, otherwise treat it as an error.

You say you do not want to place the try / catch block inside the destructor. This seems like a strange prejudice to me, but there are other ways in order.

  • You can allow the exception to propagate to the very top catch block that surrounds all your code, and handle it there. (You have a try / catch block that protects your entire application, of course :-)

  • Other ways are possible ... but the boss just sank down

+1
source

All Articles