jeudi 1 avril 2021

Wait for timer in other coroutine (Asio)

When using asio::spawn, it possible to wait for a timer in a separate coroutine? E.g., in the code below I want coroutine 2 started to print to the console and then, 5 seconds later, coroutine 2 finished.

#include <iostream>
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>

int main() {

  boost::asio::io_context io;

  // coroutine 1
  boost::asio::spawn(io, [&](boost::asio::yield_context yield) {
    boost::asio::deadline_timer timer(io, boost::posix_time::seconds(5));
    timer.async_wait(yield);
  });

  // coroutine 2
  boost::asio::spawn(io, [&](boost::asio::yield_context yield) {
    std::cout << "coroutine 2 started" << std::endl;
    // wait for coroutine 1 timer to finish
    std::cout << "coroutine 2 finished" << std::endl;
  });

  io.run();
}

Aucun commentaire:

Enregistrer un commentaire