Coroutines (C++20)

Cooperative multitasking

Interview Relevant: Modern async patterns

Coroutines (C++20)

Suspend and resume functions.

Code Examples

C++20 coroutines for cooperative concurrency.

cpp
1#include <coroutine>
2
3// Generator coroutine
4template<typename T>
5struct Generator {
6    struct promise_type {
7        T value;
8        Generator get_return_object() {
9            return Generator{handle_type::from_promise(*this)};
10        }
11        suspend_always initial_suspend() { return {}; }
12        suspend_always final_suspend() noexcept { return {}; }
13        suspend_always yield_value(T v) {
14            value = v;
15            return {};
16        }
17        void return_void() {}
18        void unhandled_exception() { throw; }
19    };
20
21    using handle_type = coroutine_handle<promise_type>;
22    handle_type handle;
23
24    bool next() {
25        handle.resume();
26        return !handle.done();
27    }
28    T value() { return handle.promise().value; }
29};
30
31// Generator function
32Generator<int> range(int start, int end) {
33    for (int i = start; i < end; i++) {
34        co_yield i;  // Suspend and return value
35    }
36}
37
38// Usage
39auto gen = range(1, 5);
40while (gen.next()) {
41    cout << gen.value() << " ";  // 1 2 3 4
42}
43
44// Coroutine keywords:
45// co_await - suspend and wait
46// co_yield - suspend and return value
47// co_return - complete coroutine

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In