Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost ASIO strand: wait for pending tasks to complete

Tags:

c++

boost

asio

Is it possible to know when all pending asynchronous tasks in strand are complete? Just like thread.join() does in the following example:

io_service service;
std::thread thread([&](){ service.run(); });

service.post(some_function);
service.post(another_function);

service.stop();
thread.join();

It would be useful for efficient execution of multiple tasks on multiple threads. Each task is more complex than ordinary function and has it's own strand. But I've found no way to wait for strand until it has 'work'. I've tried to post to a strand finalizing handler in hope it would be called last, but the order of handlers in strand is undefined, so it fires immediately.

The code with strand would be:

io_service service;
strand<io_context::executor_type> strand(make_strand(service));
std::thread thread([&](){ service.run(); });

post(strand, some_function);
post(strand, another_function);

// here we want to wait for strand to complete pending tasks

// somewhere else later
service.stop();
thread.join();

Thank you.

like image 642
san Avatar asked Oct 24 '25 18:10

san


1 Answers

You can post a use_future "completion token" to the strand. This "token" will be executed only after all other handlers in the strand have completed.

You can then wait/get on the future.

std::future<void> wait=boost::asio::post(strand, boost::asio::use_future);
wait.get();

wait.get() will succeed after all handlers have been executed.

This is also a nice way to insert "synchronisation points". Nothing prevents you from posting more handlers after this. So you can

  • post handler
  • post handler
  • post future1
  • post handler
  • post future2

and wait on the futures.

BTW, I don't know if this works with boost::asio 1.72 yet, but it will work with newer boosts. boost::asio::use_future and completion tokens are a newer addition.

like image 191
Hajo Kirchhoff Avatar answered Oct 26 '25 07:10

Hajo Kirchhoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!