chriskohlhoff / asio

Asio C++ Library
http://think-async.com/Asio
4.72k stars 1.19k forks source link

`co_spawn` and `spawn` as async initiating functions cause segfault #1372

Open kssuraaj28 opened 9 months ago

kssuraaj28 commented 9 months ago

This is a copy of this issue: https://stackoverflow.com/questions/77255378/boost-asio-co-spawn-and-spawn-as-async-initiating-functions-cause-segfault.

Here is a brief description:

Using co_spawn and spawn as async initiating functions within a stackful coroutine (using the yield completion token) cause a segfault. For instance:

Example 1 (Using co_spawn)

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

using namespace boost::asio;

io_context ioctx;
void stackful_coroutine(yield_context yield);

awaitable<void> cxx_coroutine() {
  std::cout << "In cxx_coroutine" << std::endl;
  co_return;
}

void stackful_coroutine(yield_context yield) {
  std::cout << "In stackful_coroutine" << std::endl;
  co_spawn(ioctx, cxx_coroutine(), yield);
}

int main() {
  spawn(ioctx, stackful_coroutine, detached);
  ioctx.run();
}

Example 2 (Using spawn)

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

using namespace boost::asio;

io_context ioctx;

void stackful_coroutine(yield_context yield) {
  std::cout << "In stackful_coroutine" << std::endl;
  spawn(
      ioctx, [](auto yc) { std::cout << "Spawn inside spawn" << std::endl; },
      yield);
}

int main() {
  spawn(ioctx.get_executor(), stackful_coroutine, detached);
  ioctx.run();
}

As advised by the stackoverflow answer, I am raising an issue here.

sehe commented 9 months ago

As the person analysing this on stackoverflow, I'll clarify/narrow the question I felt worth asking here is:

(I had suspicions about coroutines not being "work", but adding work-guards either in the coro stack or in the handler captures didn't seem to have a notable effect.)

klemens-morgenstern commented 9 months ago

There is a stack issue with empty functions in gcc-12.1 & 12.2 for the C++20 coroutines, so that might apply to stackful ones too.

kssuraaj28 commented 9 months ago

I've run into this issue when I use gcc as well as clang (Apple clang version 15.0.0) on a mac