-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoroutine_test.cpp
More file actions
86 lines (70 loc) · 2.41 KB
/
Copy pathcoroutine_test.cpp
File metadata and controls
86 lines (70 loc) · 2.41 KB
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
79
80
81
82
83
84
85
86
// Minimal dispatcher + coroutine example using folly
#include <folly/init/Init.h>
#include <folly/coro/Task.h>
#include <folly/coro/BlockingWait.h>
#include <folly/executors/GlobalExecutor.h>
#include <folly/coro/Collect.h>
#include <folly/executors/CPUThreadPoolExecutor.h>
#include <fmt/core.h>
#include <chrono>
#include <string>
#include <thread>
#include <sstream>
using folly::coro::Task;
using namespace std::chrono_literals;
// Helper to convert thread ID to string for fmt
inline std::string thread_id_str() {
std::ostringstream oss;
oss << std::this_thread::get_id();
return oss.str();
}
struct Pulse {
std::string name;
std::chrono::milliseconds duration;
};
class Dispatcher {
public:
void submit(const Pulse& pulse) const {
fmt::print("[tid={}] Dispatching pulse '{}' for {} ms\n",
thread_id_str(),
pulse.name,
pulse.duration.count());
}
};
template<typename T>
folly::coro::Task<T> submit_cpu(folly::Executor* executor,
folly::coro::Task<T>&& task) {
co_return co_await std::move(task).scheduleOn(executor);
}
Task<int> measure(int milliseconds) {
fmt::print("[tid={}] measure start\n", thread_id_str());
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
fmt::print("[tid={}] Measured: {}\n", thread_id_str(), milliseconds);
co_return milliseconds + 1;
}
/// Some other sequence of pulses
Task<int> sequence(Dispatcher& dispatcher) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
dispatcher.submit(Pulse{"A", 5ms});
dispatcher.submit(Pulse{"B", 5ms});
dispatcher.submit(Pulse{"C", 5ms});
dispatcher.submit(Pulse{"D", 5ms});
co_return 3;
}
Task<int> program(Dispatcher& dispatcher, folly::CPUThreadPoolExecutor* cpuPool) {
auto [result1, result2] =
co_await folly::coro::collectAll(measure(2).scheduleOn(cpuPool),
sequence(dispatcher));
int result3{0};
if (result1 == 3) { result3 = co_await sequence(dispatcher); }
co_return result1 + result2 + result3;
}
int main(int argc, char** argv) {
folly::init(&argc, &argv);
Dispatcher dispatcher;
folly::CPUThreadPoolExecutor cpuPool{3};
/// This is the main entrypoint for the coroutine.
int result = folly::coro::blockingWait(program(dispatcher, &cpuPool));
fmt::print("Result: {}\n", result);
return 0;
}