9

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?

Naios
  • 1,513
  • 1
  • 12
  • 26
  • Have you checked the `${boost_root}/libs/asio/example/cpp11/executors/pipeline.cpp` ? I think you don't need more then one `io_context`. – Victor Gubin May 30 '18 at 18:24

1 Answers1

1

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;
beerboy
  • 1,304
  • 12
  • 12
  • Sadly, setting a cancel flag isn't enough here, since the work will contain references to code which is placed in a shared library that is unloaded after the work was removed / canceled and this willl lead to access violations. So it is really required to remove the work from the io_context as stated by the question. – Naios May 29 '18 at 14:59
  • @Naios - It doesn't matter if there are any invalid pointers captured in job lambda. If job will just return immediately due to cancel, it will not access the invalid memory pointed by captured pointers. – Michał Jaroń Jan 25 '23 at 12:44