Coroutines in C++: Avoiding the Most Common Gotchas

2025-09-18

C++ coroutines are a powerful feature, but they can be tricky. Here are some of the most common problems you'll encounter and how to deal with them.

This is a classic issue. Your coroutine might just hang there, doing nothing. This usually happens when the promise type's await_transform method isn't correctly implemented. The coroutine is suspended, but the caller never gets a way to resume it.

// The promise type doesn't provide a way to resume.
struct simple_promise {
    auto get_return_object() { /* ... */ }
    auto initial_suspend() { return std::suspend_always{}; }
    auto final_suspend() noexcept { return std::suspend_always{}; }
    void return_void() {}
    void unhandled_exception() {}
};

struct simple_task {
    using promise_type = simple_promise;
    /* ... */
};

simple_task do_something() {
    co_await std::suspend_always{}; // Suspends here
    co_return; // Never reaches this point
}

void main() {
    auto task = do_something();
    // What now? We have no handle to resume the task.
}

The best way to fix this is to use a well-designed coroutine type that provides a handle to resume execution. The initial_suspend and final_suspend should work in tandem with the return object to manage the coroutine's state.

// A simple coroutine type that provides a handle to resume.
struct resumable_promise;
struct resumable_task {
    using promise_type = resumable_promise;
    std::coroutine_handle<resumable_promise> handle;
};

struct resumable_promise {
    auto get_return_object() {
        return resumable_task{ std::coroutine_handle<resumable_promise>::from_promise(*this) };
    }
    auto initial_suspend() { return std::suspend_always{}; }
    auto final_suspend() noexcept { return std::suspend_always{}; }
    void return_void() {}
    void unhandled_exception() {}
};

resumable_task do_something() {
    // This will suspend and return a resumable_task handle.
    co_await std::suspend_always{};
    co_return;
}

void main() {
    auto task = do_something();
    if (task.handle) {
        task.handle.resume(); // We can now resume it!
    }
}

This happens when you try to resume a coroutine after it has already finished executing. This can lead to undefined behavior and crashes, since the memory for the coroutine frame has likely been deallocated.

resumable_task do_something() {
    // Coroutine finishes immediately.
    co_return;
}

void main() {
    auto task = do_something();
    // The coroutine is already done!
    task.handle.resume(); // UB! Crash! 
}

Always check if a coroutine handle is done before resuming it. The std::coroutine_handle::done() method is your friend!

resumable_task do_something_else() {
    co_await std::suspend_always{};
    co_return;
}

void main() {
    auto task = do_something_else();

    // Check if it's done before resuming.
    if (!task.handle.done()) {
        task.handle.resume();
    }

    // Now it's done, so don't resume again!
    if (!task.handle.done()) {
        // This won't be executed.
        task.handle.resume();
    }
}

Sometimes, a coroutine-based function can still block the main thread. This often happens because the awaitable object is not truly asynchronous. For example, it might perform a long-running synchronous operation before suspending.

#include <iostream>
#include <thread>
#include <chrono>

struct long_op_awaitable {
    bool await_ready() { return false; }
    void await_suspend(std::coroutine_handle<> h) {
        std::this_thread::sleep_for(std::chrono::seconds(5)); // Blocks the thread! 
        h.resume();
    }
    void await_resume() {}
};

resumable_task do_blocking_work() {
    std::cout << "Starting blocking work..." << std::endl;
    co_await long_op_awaitable{};
    std::cout << "Finished blocking work!" << std::endl;
    co_return;
}

void main() {
    std::cout << "Main thread start." << std::endl;
    auto task = do_blocking_work();
    // This will block for 5 seconds because await_suspend is synchronous.
    if (task.handle) task.handle.resume();
    std::cout << "Main thread finished." << std::endl;
}

True asynchronous behavior requires delegating the work to another thread or an event loop. A common pattern is to post the resume operation to a thread pool.

#include <iostream>
#include <thread>
#include <chrono>

// An awaitable that offloads work to a new thread.
struct async_awaitable {
    std::jthread worker;
    std::coroutine_handle<> handle;

    bool await_ready() { return false; }
    void await_suspend(std::coroutine_handle<> h) {
        handle = h;
        worker = std::jthread([this]() {
            std::this_thread::sleep_for(std::chrono::seconds(5));
            handle.resume(); // Resume from the worker thread.
        });
    }
    void await_resume() {}
};

resumable_task do_async_work() {
    std::cout << "Starting async work..." << std::endl;
    co_await async_awaitable{};
    std::cout << "Finished async work!" << std::endl;
    co_return;
}

void main() {
    std::cout << "Main thread start." << std::endl;
    auto task = do_async_work();
    // The main thread is not blocked and can do other things.
    std::cout << "Main thread continues..." << std::endl;
    
    // We need to ensure the worker thread and coroutine complete before main exits.
    // A more robust solution would use an event loop or a task scheduler.
    // Here, we'll just wait a bit for demonstration.
    if (task.handle) {
        // In a real application, the scheduler would manage this.
    }
    std::this_thread::sleep_for(std::chrono::seconds(6));
    std::cout << "Main thread finished." << std::endl;
}

cpp



Demystifying C++ Filesystem Hashing: A Guide to std::hash

One of the main "gotchas" with this feature is inconsistent hashing. The hash value can change based on the specific representation of the path


Common Issues and Alternatives for std::ranges::elements_of in C++

In C++, std::ranges::elements_of is a cool tool that lets you seamlessly "flatten" a range of ranges into a single, continuous range


Understanding std::moneypunct in C++: Troubleshooting and Customization

std::moneypunct is a C++ standard library facet that defines how monetary values are represented in a specific locale. It provides information like



C++ std::multimap::upper_bound: Common Issues and the equal_range() Solution

The std::multimap::upper_bound function returns an iterator pointing to the first element in the multimap that has a key strictly greater than the one you're searching for


A Friendly Guide to std::unordered_multiset::contains

The std::unordered_multiset::contains method is a simple and efficient way to check if an element exists in an std::unordered_multiset


C++ Random Number Generation: Common Mersenne Twister Pitfalls and Solutions

When you're using the Mersenne Twister, you'll often run into issues related to seeding. The seed is the initial value that determines the entire sequence of numbers


C++ std::tmpfile(): Common Problems and Modern Alternatives

A frequent mistake is losing the file before you're done with it. Since std::tmpfile() creates a file that is automatically deleted when the FILE pointer is closed


Troubleshooting C++'s std::vformat_to: Lifetime and Runtime Error Fixes

std::vformat_to is a powerful C++ utility for formatting data into an output buffer, similar to C's sprintf, but it's type-safe


Mastering C++ I/O: The operator<< and String Views

If you were trying to use operator<< on a std::string, it would also work because std::string can be implicitly converted to std::basic_string_view


Don't Dereference the End: Common Mistakes with std::basic_string::cend and How to Fix Them

Hey there! Let's dive into some of the common issues with std::basic_string::cend in C++ and explore some great alternatives