Skip to content

Commit 440a498

Browse files
committed
added stdc++ coroutine example
1 parent 1f9d47e commit 440a498

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

stdc++/coroutine.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include "stm32f4_discovery.h"
2+
#include <thread>
3+
#include <coroutine>
4+
5+
struct Generator
6+
{
7+
struct promise_type
8+
{
9+
int current_value;
10+
11+
Generator get_return_object() { return Generator{std::coroutine_handle<promise_type>::from_promise(*this)}; }
12+
13+
std::suspend_always initial_suspend() { return {}; }
14+
std::suspend_always final_suspend() noexcept { return {}; }
15+
std::suspend_always yield_value(int value) { current_value = value; return {}; }
16+
17+
void return_void() {}
18+
void unhandled_exception() { std::terminate(); }
19+
};
20+
21+
std::coroutine_handle<promise_type> handle;
22+
23+
~Generator() { if (handle) handle.destroy(); }
24+
25+
bool next() { handle.resume(); return !handle.done(); }
26+
int value() { return handle.promise().current_value; }
27+
};
28+
29+
Generator counter(int value)
30+
{
31+
for (;;)
32+
{
33+
std::this_thread::sleep_for(std::chrono::seconds{1});
34+
co_yield value;
35+
}
36+
}
37+
38+
int main()
39+
{
40+
auto gen = counter(0);
41+
auto led = device::Led();
42+
43+
while (gen.next())
44+
led.tick();
45+
}

0 commit comments

Comments
 (0)