C++20 coroutine unexpectedly re-enters suspended state in custom awaiter implementation
I've searched everywhere and can't find a clear answer... I'm currently implementing a coroutine in C++20 that uses a custom awaiter, but I'm running into an issue where the coroutine seems to unexpectedly re-enter its suspended state after being resumed. This is causing parts of my code to execute multiple times unexpectedly. Here's a simplified structure of my coroutine and the custom awaiter: ```cpp #include <coroutine> #include <iostream> #include <thread> struct MyAwaiter { bool await_ready() noexcept { return false; } void await_suspend(std::coroutine_handle<> h) noexcept { std::thread([h]() { std::this_thread::sleep_for(std::chrono::seconds(1)); h.resume(); }).detach(); } void await_resume() noexcept {} }; struct MyCoroutine { struct promise_type { MyCoroutine get_return_object() { return MyCoroutine{this}; } std::suspend_always initial_suspend() noexcept { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void return_void() noexcept {} void unhandled_exception() { std::terminate(); } }; MyCoroutine(promise_type* p) : handle(std::coroutine_handle<promise_type>::from_promise(*p)) {} std::coroutine_handle<promise_type> handle; void resume() { handle.resume(); } }; MyCoroutine myCoroutine() { std::cout << "Coroutine started!\n"; co_await MyAwaiter(); std::cout << "Coroutine resumed!\n"; } int main() { auto coroutine = myCoroutine(); coroutine.handle.resume(); std::cout << "Main function finished!\n"; } ``` When I run this code, I see the output: ``` Coroutine started! Main function finished! Coroutine resumed! Coroutine resumed! ``` It appears that the coroutine resumes twice. I suspect that the issue lies in the way I'm handling the coroutine handle in the `await_suspend` method, but I'm not sure how to debug this. I've tried modifying the lifetime of the handle and using different synchronization mechanisms, like `std::mutex`, but the behavior remains unchanged. How can I prevent this unexpected re-entry into the coroutine? Am I missing something obvious? What am I doing wrong?