Created
January 10, 2023 20:58
-
-
Save tom-code/10d16a37a5cd5af8fa06068825f12058 to your computer and use it in GitHub Desktop.
c++20 coroutine minidemo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <concepts> | |
#include <experimental/coroutine> | |
#include <iostream> | |
#include <unistd.h> | |
#include <thread> | |
#include <vector> | |
struct awaitable { | |
std::experimental::coroutine_handle<> _h; | |
bool await_ready() { return false; } | |
void await_suspend(std::experimental::coroutine_handle<> h) { | |
_h = h; | |
} | |
int val = 0; | |
int await_resume() { return val;} | |
}; | |
struct task | |
{ | |
struct promise_type | |
{ | |
task get_return_object() { return {}; } | |
std::experimental::suspend_never initial_suspend() { printf("initial\n"); return {}; } | |
std::experimental::suspend_never final_suspend() noexcept { printf("final\n"); return {}; } | |
void return_void() { printf("return\n");} | |
void unhandled_exception() {} | |
}; | |
}; | |
std::vector<awaitable*> waiters; | |
task run(int n) { | |
awaitable a; | |
waiters.push_back(&a); | |
printf("start %d\n", n); | |
auto x = co_await a; | |
printf("done %d %d\n", n, x); | |
}; | |
int main() { | |
printf("s1\n"); | |
for (int i=0; i<5; i++) run(i); | |
printf("s2\n"); | |
std::thread t( []{ | |
sleep(1); | |
for (auto w: waiters) { | |
w->val = 100; | |
w->_h.resume(); | |
sleep(1); | |
} | |
}); | |
t.join(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment