capypad
0 Tage Serie
cpp / expert
Snippet

C++20 Coroutinen: Minimales Promise-Interface

C++20-Coroutinen sind Funktionen, die ihre Ausführung unterbrechen und fortsetzen können. Sie werden durch einen 'promise_type' gesteuert, der das Verhalten der Coroutinen-State-Machine definiert, z. B. wo sie anfangs unterbrochen wird.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <coroutine>
#include <iostream>
 
struct Resumable {
struct promise_type {
Resumable get_return_object() { return {}; }
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
};
 
Resumable simple_coro() {
std::cout << "Step 1\n";
co_await std::suspend_always{};
std::cout << "Step 2\n";
}
 
int main() {
auto handle = simple_coro(); // Suspended at start
}
Erklärung
1
struct promise_type
Die obligatorische innere Struktur, die als Controller für den Lebenszyklus der Coroutine fungiert.
2
co_await std::suspend_always{};
Unterbricht die Ausführung der Coroutine und gibt die Kontrolle an den Aufrufer zurück.