forked from Codesire-Deng/co_context
-
Notifications
You must be signed in to change notification settings - Fork 0
/
when_any.cpp
52 lines (46 loc) · 1.16 KB
/
when_any.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
#include "co_context/all.hpp"
#include <iostream>
#include <variant>
using namespace co_context;
task<int> f0() {
printf("f0 start.\n");
co_await timeout(std::chrono::seconds{1});
printf("f0 done.\n");
co_return 1;
}
task<const char *> f1() {
printf("f1 done.\n");
co_return "f1 Great!";
}
task<void> f2() {
printf("f2 start.\n");
co_await timeout(std::chrono::seconds{2});
printf("f2 done.\n");
co_return;
}
task<> run() {
// var : std::variant<std::monostate, int, const char *>;
auto [idx, var] = co_await any(f0(), f1(), f2());
std::cout << idx << " finished!\n";
std::visit(
overloaded{
[](std::monostate) { std::cout << "impossible\n"; },
[](int x) { std::cout << x << " : int\n"; },
[](const char *s) { std::cout << s << " : string\n"; },
},
var
);
{
std::cout << "--------------\n";
std::cout << "3 * f2 start!\n";
uint32_t idx = co_await any<unsafe>(f2(), f2(), f2());
std::cout << idx << " finished!\n";
}
}
int main() {
io_context ctx;
ctx.co_spawn(run());
ctx.start();
ctx.join();
return 0;
}