标签云

微信群

扫码加入我们

WeChat QR Code

I have a boost::thread which performs synchronous reads on a boost::asio::serial_port. When I destroy an instance of the class which contains both, I want the thread to end gracefully even if its blocked in a read call. How can I do this?Looking at the docs, I tried cancel, but it works only for asynchronous reads/writes. Then I tried close, but I got an exception and it wasn't the kind you can recover from. Perhaps using send_break or native_handle? (this is Windows and portability's not critical)Update: I also tried to stop the io_service I passed to the serial port object's constructor, but the read wasn't unblocked.Edit: The exception is actually "catchable", but I'd hate to put a try/catch block inside a destructor, and refactoring the code to do the shutdown process outside the destructor would trigger lots of changes in upper layers. So I'd only go for this solution if some Boost authority says there is no other way.


And that's why Boost::Asio isn't called Boost::SioAndAsio :)

2019年04月18日32分16秒

You mean boost::asio::serial_port is not meant to be read or written synchronously? I went for synchronous read/write to avoid polling... If they allow me to read and write that way, which works wonderfully and doesn't waste CPU cycles, they should offer a way to end gracefully.

2019年04月18日32分16秒

Yes, I wanted to do the same a few days ago.

2019年04月18日32分16秒

Did you ask at the Boost mailing lists and were told there was no other way?

2019年04月18日32分16秒

No, but I've found some pointers, and read most of the asio documentation. Look, at this question: stackoverflow.com/questions/1856957/…

2019年04月18日32分16秒

I actually ignored the exception and hit continue in the debugger, but since it happened inside a destructor, it irked me too much too put a try/catch block there. I could refactor my code to do this outside the destructor, but this would ripple up many layers of destructors calls and would be pretty bothersome. I would only accept this as a last resort solution. I edited my question accordingly.

2019年04月18日32分16秒

About exceptions in destructors, there are pitfalls. But I think that the dangerous scenario mentioned in the faq does not apply. Besides, I asked at the boost-users mail list and they told me to catch boost::asio::error::operation_aborted, which allows me to distinguish shutdown from error, I believe. I'll try this out and if it works I'll accept your answer.

2019年04月19日32分16秒

I tried to catch std::exception and ran into Runtime Check Failure #0 (the value of ESP was not preserved or something like that). I gave up and decided to use async_read and write + Boost Windows event equivalent to perform blocking reads and writes.

2019年04月19日32分16秒