gpt4 book ai didi

c++ - 防止 boost::asio::io_context 在空轮询调用时停止

转载 作者:行者123 更新时间:2023-12-01 14:22:23 30 4
gpt4 key购买 nike

此代码调用已发布的句柄

    boost::asio::io_context ioc;
boost::asio::post(ioc, []{ std::cout << "lol" << std::endl; });
ioc.poll();
而这不会:
    boost::asio::io_context ioc;
ioc.poll(); // empty, set internal state to stopped_
boost::asio::post(ioc, []{ std::cout << "lol" << std::endl; });
ioc.poll(); // doesn't work as stopped() now returns true
Live example
是设计的吗?如果是,为什么?我可以配置 io_context以某种方式改变这种行为?

最佳答案

io_service/io_context 旨在在它们用完工作时停止¹。
io_service 的文档和 io_context 包含:

Stopping the io_context from running out of work

Some applications may need to prevent an io_context object's run() call from returning when there is no more work to do. For example, the io_context may be being run in a background thread that is launched prior to the application's asynchronous operations. The run() call may be kept running by creating an object of type boost::asio::executor_work_guard<io_context::executor_type>:

boost::asio::io_context io_context;
boost::asio::executor_work_guard<boost::asio::io_context::executor_type>
= boost::asio::make_work_guard(io_context);
...

To effect a shutdown, the application will then need to call the io_context object's stop() member function. This will cause the io_context run() call to return as soon as possible, abandoning unfinished operations and without permitting ready handlers to be dispatched.

Alternatively, if the application requires that all operations and handlers be allowed to finish normally, the work object may be explicitly reset.

boost::asio::io_context io_context;
boost::asio::executor_work_guard<boost::asio::io_context::executor_type>
= boost::asio::make_work_guard(io_context);
...
work.reset(); // Allow run() to exit.

请注意,“老式”Asio 界面使用了一个不太通用的 io_service::work目的:
io_service ios;
io_service::work work(ios); // old interface!
这将需要您做额外的工作才能重置它:
asio::io_service ios;
std::optional<asio::io_service::work> work(ios);
// ...
work.reset();
重启
最后,当上下文确实用完工作时,您将不得不 restart()在重新使用它之前:
enter image description here
基本原理
我认为设计的基本原理来自图书馆没有任何
关于服务如何在调度和线程方面运行的意见,在
结合保证 io_context/ io_service必须是
线程安全²。见 docs forbackground .

¹ 旁注:同样, thread_pool (这是一个 execution_context 就像 io_context 是)不是为重复使用而设计的(参见例如 Boost asio thread_pool join does not wait for tasks to be finished )
² 当然,对象生命周期(构造/销毁)除外

关于c++ - 防止 boost::asio::io_context 在空轮询调用时停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63378018/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com