In the following code, the parameter of the session coroutine is passed by reference.
#include <boost/asio.hpp>
#include <iostream>
boost::asio::awaitable<void> session(const std::string& name)
{
std::cout << "Starting " << name << std::endl;
auto executor = co_await boost::asio::this_coro::executor;
}
int main()
{
boost::asio::io_context io_context;
co_spawn(io_context, session("ServerA"), boost::asio::detached);
co_spawn(io_context, session("ServerB"), boost::asio::detached);
io_context.run();
return 0;
}
For some reason that I don't understand, the above code results in printing Starting ServerB twice.
> g++ -std=c++20 ../test-coro.cpp -o test-coro && ./test-coro
Starting ServerB
Starting ServerB
But when I change the coroutine parameter to pass by value, it will correctly print both Starting ServerA and Starting ServerB
#include <boost/asio.hpp>
#include <iostream>
boost::asio::awaitable<void> session(std::string name)
{
std::cout << "Starting " << name << std::endl;
auto executor = co_await boost::asio::this_coro::executor;
}
int main()
{
boost::asio::io_context io_context;
co_spawn(io_context, session("ServerA"), boost::asio::detached);
co_spawn(io_context, session("ServerB"), boost::asio::detached);
io_context.run();
return 0;
}
> g++ -std=c++20 ../test-coro.cpp -o test-coro && ./test-coro
Starting ServerA
Starting ServerB
Is it expected or this is a compiler/library bug? If it is expected, then what's the reasoning for it?
Environment:
Arch Linux 5.18.16-arch1-1
gcc (GCC) 12.2.0
boost version 1.79