从io_context中删除工作或使用多个io_context对象

Den*_*ank 8 c++ boost asynchronous event-loop boost-asio

目前,我试图使人们有可能删除工作通过排队post或者dispatchio_context.这项工作由少量的库格组排队,工作可以一次性删除:

boost::asio::io_context context;

auto work = [] {
  // ...
};
boost::asio::post(context, std::move(work));

// ... now I want to remove the work
Run Code Online (Sandbox Code Playgroud)

是否有asio库提供的功能?

目前我正在使用的应用程序是使用io_context::run()从多个线程调用的线程池.

我的想法是,我可以创建io_context由线程池调度的多个s,以便一个io_context代表可以通过删除的组io_context::stop().所有io_contexts都将被保存在一个列表中,然后汇集到一个列表中以用于未完成的事件.

但是我相信汇集或等待很多人io_context可能会导致性能问题.有不同的解决方案吗?

bee*_*boy 1

不,没有从 中删除已发布职位的机制io_context。或者,您可以修改作业以在运行之前检查是否设置了“取消标志”(未经测试):

// create a cancellation flag
const auto cancel = std::make_shared<std::atomic<bool> >();

auto work = [=] {

    // check to see if the flag has been set
    // if so, return without performing our task
    if(*cancel)
        return;

    // perform some task
};

// post our job
boost::asio::post(context, std::move(work));

...

// cancel all jobs checking this flag
*cancel = true;
Run Code Online (Sandbox Code Playgroud)