在检查 1.66.0 版本中 boost::asio 的文档时,我注意到 io_context 构造函数提供了一个 concurrency_hint
。范围。阅读文档后,我不确定是否可以使用 BOOST_ASIO_CONCURRENCY_HINT_UNSAFE_IO
。
我有以下情况:
- 我有一个
io_context
来执行 IO。ioc.run()
从单线程执行。 - 在此线程中,执行了一些使用异步调用的网络 IO。
- 其他线程调用
boost::asio::dispatch(ioc, ...)
在IO线程上执行代码。
我想弄清楚 concurrency hint 是什么在上述情况下可以安全使用该值:
- 不使用并发提示是可以的(例如
BOOST_ASIO_CONCURRENCY_HINT_SAFE
),但比使用提示慢。 - 使用
1
即可。 - 使用
BOOST_ASIO_CONCURRENCY_HINT_UNSAFE
是不行的,因为它不允许异步调用。
我不清楚的是 BOOST_ASIO_CONCURRENCY_HINT_UNSAFE_IO
。文档说:
This special concurrency hint disables locking in the reactor I/O. This hint has the following restrictions:
— Care must be taken to ensure that run functions on the io_context, and all operations on the context's associated I/O objects (such as sockets and timers), occur in only one thread at a time.
我想知道在使用此并发提示时从另一个线程执行 boost::asio::dispatch
是否安全。
最佳答案
自 boost::asio::dispatch
¹ ends up calling io_context::dispatch
我会得出结论,如果您从另一个线程调用它,则使用 BOOST_ASIO_CONCURRENCY_HINT_UNSAFE_IO
是不行的:
— Care must be taken to ensure that run functions on the io_context, and all operations on the context's associated I/O objects (such as sockets and timers), occur in only one thread at a time.
¹ post/defer 相同
关于c++ - io_context 并发提示 (BOOST_ASIO_CONCURRENCY_HINT_UNSAFE_IO),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49266778/