Minimal awaitable example

535 views Asked by At

I wonder why the following programme crashes. How to use awaitable not with boost::asio::async_write/async_read functions.

Let's see:

#include <iostream>

#include <boost/asio/io_context.hpp>
#include <boost/asio/co_spawn.hpp>
#include <boost/asio/detached.hpp>

using boost::asio::io_context;
using boost::asio::co_spawn;
using boost::asio::awaitable;
using boost::asio::detached;

awaitable<void> task() {
  std::cout << "hello" << std::endl;
  return awaitable<void>{};
}

int main() {
  try {
    boost::asio::io_context io_context(1);

    co_spawn(io_context, task(), detached);

    io_context.run();
  } catch(const std::exception &ex) {
    std::cerr << ex.what() << std::endl;
  }
  return 0;
}

This results in

hello
(Segmentation fault)

What is wrong about it?

UPD: self-solved. I should just use co_return. Thus it must be the following:

awaitable<void> task() {
  std::cout << "hello" << std::endl;
  co_return;
}
1

There are 1 answers

0
unegare On BEST ANSWER

digging into the sources of boost::asio::awaitable, I figured out that I just should make use of co_return keyword. Surprisingly, it is not shipped with boost. It is enabled either by -fcoroutines flag or -std=c++20. Unexpectedly. Having said that, it is solved.