Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove work from a io_context or using multiple io_context objects

Currently I'm trying to make it possible to remove work queued through post or dispatch to an io_context. The work is queued by a small amount of queuer groups for which the work shall be removeable all at once:

boost::asio::io_context context;

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

// ... now I want to remove the work

Is there such a functionality provided by the asio library?

Currently the application I'm working on, is using a thread pool which invokes io_context::run() from multiple threads.

My idea was that I could create multiple io_contexts that are dispatched by the thread pool such that one io_context represents a group that could be removed through io_context::stop(). All io_contexts would be held inside a single list which is then pooled for outstanding events.

However I believe that pooling or waiting for many io_contexts could lead to performance issues. Is there a different solution?

like image 733
Denis Blank Avatar asked May 20 '18 03:05

Denis Blank


1 Answers

No, there's no mechanism for removing posted jobs from an io_context. Alternatively, you could modify your jobs to check if a 'cancel flag' is set before they run (untested):

// 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;
like image 85
beerboy Avatar answered Sep 26 '22 02:09

beerboy