Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Coroutines

A coroutine can suspend execution and resume later while preserving the state it needs. The keywords co_await, co_yield, and co_return cooperate with a promise type and a coroutine handle; they do not automatically start a thread or scheduler.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

co_await expression; co_yield expression; co_return [expression];

A coroutine is a function whose body contains co_await, co_yield, or co_return. When it suspends, it preserves the state needed to continue. Control can return to its caller or resumer, but if the awaiter's await_suspend() returns a handle to another coroutine, control transfers directly to that coroutine. This does not imply automatic parallel execution: using a coroutine alone creates neither a thread nor a scheduler.

co_await uses the awaiter protocol: await_ready() checks readiness, await_suspend() handles suspension, and await_resume() supplies the result. Not every co_await actually leaves the coroutine suspended. co_yield value awaits the result of promise.yield_value(value) without applying the promise's await_transform. An explicitly written co_await promise.yield_value(value) uses await_transform if the promise type provides it, so the replacement can change behavior or fail to compile. co_return finishes the coroutine body rather than passing a value directly to its caller.

The promise type, commonly available as the return type's promise_type, controls the result object, initial and final suspension, completion, and exception handling. <coroutine> supplies std::coroutine_handle and std::suspend_always. A handle does not manage the state's lifetime by itself: responsibility for destruction must be explicit.

In the example, Task is a noncopyable, nonmovable owner. initial_suspend() delays execution of the body, and final_suspend() retains the state for destruction by the destructor. The example uses std::suspend_always, which does not transfer control directly to another coroutine. Two resumptions print 1 and 2; the third does nothing because of done(). Resuming a completed or nonsuspended coroutine causes undefined behavior. After the coroutine state has been destroyed, attempting to resume through a handle to that state also causes undefined behavior, but assigning nullptr to reset that handle is well-defined. Objects referred to through references must remain alive long enough.

This entry targets C++23; the repository compiler flag does not attest production runtime support. The supplied document is an evolving working draft, not a frozen C++23 edition. The example requires local verification and deliberately calls std::terminate() for an unhandled exception.

Examples

#include <coroutine>
#include <exception>
#include <iostream>

class Task {
public:
    struct promise_type {
        Task get_return_object() {
            return Task{std::coroutine_handle<promise_type>::from_promise(*this)};
        }
        std::suspend_always initial_suspend() noexcept { return {}; }
        std::suspend_always final_suspend() noexcept { return {}; }
        void return_void() noexcept {}
        void unhandled_exception() noexcept { std::terminate(); }
    };

    using Handle = std::coroutine_handle<promise_type>;
    explicit Task(Handle handle) noexcept : handle_(handle) {}
    Task(const Task&) = delete;
    Task& operator=(const Task&) = delete;
    ~Task() { handle_.destroy(); }

    void resume() {
        if (!handle_.done()) {
            handle_.resume();
        }
    }

private:
    Handle handle_;
};

Task steps() {
    std::cout << "1\n";
    co_await std::suspend_always{};
    std::cout << "2\n";
    co_return;
}

int main() {
    auto task = steps();
    task.resume();
    task.resume();
    task.resume();
}

Result

1
2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources