-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path01_CoroSimpleExample.cpp
78 lines (57 loc) · 1.97 KB
/
01_CoroSimpleExample.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright (c) 2024 Damian Nowakowski. All rights reserved.
// This is the simpliest c++ coroutine example possible.
// For more details check: https://github.com/zompi2/cppcorosample
#include <iostream>
#include <coroutine>
// Forward declaration of the Promise so it can be used for a Handle definition
struct CoroPromise;
// Definition of the coroutine Handle using our Promise
struct CoroHandle : std::coroutine_handle<CoroPromise>
{
// Tell the handle to use our Promise
using promise_type = ::CoroPromise;
// Called when the coroutine has been resumed
void await_resume() {}
// Indicated that coroutine can be suspended
bool await_ready() { return false; }
// Called when the coroutine has been suspended
void await_suspend(std::coroutine_handle<CoroPromise> Handle) {};
};
// Definition of the coroutine Promise
struct CoroPromise
{
// Called in order to construct the coroutine Handle
CoroHandle get_return_object() { return { CoroHandle::from_promise(*this) }; }
// Do not suspend when the coroutine starts
std::suspend_never initial_suspend() noexcept { return {}; }
// Do not suspend when the coroutine ends
std::suspend_never final_suspend() noexcept { return {}; }
// Called when co_return void is used
void return_void() {}
// Called when exception occurs
void unhandled_exception() {}
};
// Definition of the coroutine function
CoroHandle CoroTest()
{
std::cout << "CoroTest Before Suspend\n";
// Suspends the function. Returns the handle.
co_await CoroHandle();
std::cout << "CoroTest After Resume\n";
}
// Main program
int main()
{
// Calls the coroutine function. Stores the Coroutine handle for it.
CoroHandle handle = CoroTest();
std::cout << "CoroTest Resuming\n";
// Resumes the suspended coroutine function.
handle.resume();
return 0;
}
/**
The program should output:
CoroTest Before Suspend
CoroTest Resuming
CoroTest After Resume
*/