chriskohlhoff/asio

Failed to switch thread to specified executor thread using dispatch in coroutine

zhllxt opened this issue · 1 comments

asio::awaitable<void> test(asio::io_context& ctx2)
{
	fmt::print("coro thread: {}\n", std::this_thread::get_id());
	// output: 18472 == thread1

	co_await asio::dispatch(ctx2.get_executor(), asio::use_awaitable);

	fmt::print("thread after coro switch: {}\n", std::this_thread::get_id());
	// output: 18472 == thread1, switch failed

	asio::dispatch(ctx2.get_executor(), [&]() mutable
	{
		fmt::print("thread after async switch: {}\n", std::this_thread::get_id());
		// output: 7652 == thread2, switch successed
	});
}

int main()
{
	asio::io_context ctx1, ctx2;

	asio::co_spawn(ctx1.get_executor(), test(ctx2), asio::detached);

	std::thread([&]() mutable
	{
		fmt::print("thread1: {}\n", std::this_thread::get_id()); // output: 18472
		while (true)
			ctx1.run();
	}).detach();

	std::thread([&]() mutable
	{
		fmt::print("thread2: {}\n", std::this_thread::get_id()); // output: 7652
		while (true)
			ctx2.run();
	}).detach();

	while (std::getchar() != '\n');
}

ok, i know.

co_await asio::dispatch(asio::bind_executor(ctx2.get_executor(), asio::use_awaitable));