-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_loop_test.cpp
More file actions
366 lines (282 loc) · 9.2 KB
/
Copy pathrun_loop_test.cpp
File metadata and controls
366 lines (282 loc) · 9.2 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#include <gtest/gtest.h>
import std;
import mcpplibs.cmp;
namespace {
using mcpplibs::cmp::RunLoop;
using mcpplibs::cmp::Task;
using Scheduler = RunLoop::Scheduler;
static_assert(std::default_initializable<RunLoop>);
static_assert(!std::copy_constructible<RunLoop>);
static_assert(!std::move_constructible<RunLoop>);
static_assert(!std::is_copy_assignable_v<RunLoop>);
static_assert(!std::is_move_assignable_v<RunLoop>);
static_assert(!std::default_initializable<Scheduler>);
static_assert(std::copy_constructible<Scheduler>);
static_assert(std::move_constructible<Scheduler>);
static_assert(std::equality_comparable<Scheduler>);
Task<int> lazy_value(bool& started) {
started = true;
co_return 42;
}
Task<void> increment(int& value) {
++value;
co_return;
}
Task<std::unique_ptr<int>> make_move_only_value() {
co_return std::make_unique<int>(7);
}
Task<void> do_nothing() {
co_return;
}
Task<std::thread::id> schedule_once(Scheduler scheduler) {
co_await scheduler.schedule();
co_return std::this_thread::get_id();
}
Task<int> schedule_many_times(Scheduler scheduler, int count) {
for (int index { 0 }; index < count; ++index) {
co_await scheduler.schedule();
}
co_return count;
}
Task<void> fail_after_scheduling(Scheduler scheduler) {
co_await scheduler.schedule();
throw std::runtime_error { "scheduled task failed" };
}
Task<void> run_nested(RunLoop& loop) {
loop.run(do_nothing());
co_return;
}
class ResumeOnNewThread final {
private:
std::thread* worker_ {};
public:
explicit ResumeOnNewThread(std::thread& worker) noexcept
: worker_ { &worker } {}
[[nodiscard]] constexpr bool await_ready() const noexcept {
return false;
}
void await_suspend(std::coroutine_handle<> continuation) const {
// 新线程可能立即恢复协程,因此启动后不再读取 awaiter 成员。
auto* const worker = worker_;
*worker = std::thread { [continuation] {
continuation.resume();
} };
}
constexpr void await_resume() const noexcept {}
};
Task<std::pair<std::thread::id, std::thread::id>> leave_and_return(
Scheduler scheduler,
std::thread& worker) {
co_await ResumeOnNewThread { worker };
const auto workerThread = std::this_thread::get_id();
co_await scheduler.schedule();
co_return std::pair { workerThread, std::this_thread::get_id() };
}
Task<std::thread::id> finish_on_new_thread(std::thread& worker) {
co_await ResumeOnNewThread { worker };
co_return std::this_thread::get_id();
}
class ManualSuspend final {
private:
std::coroutine_handle<>* continuation_ {};
std::latch* suspended_ {};
public:
ManualSuspend(
std::coroutine_handle<>& continuation,
std::latch& suspended) noexcept
: continuation_ { &continuation }, suspended_ { &suspended } {}
[[nodiscard]] constexpr bool await_ready() const noexcept {
return false;
}
void await_suspend(std::coroutine_handle<> continuation) const noexcept {
*continuation_ = continuation;
suspended_->count_down();
}
constexpr void await_resume() const noexcept {}
};
Task<void> suspend_manually(
std::coroutine_handle<>& continuation,
std::latch& suspended) {
co_await ManualSuspend { continuation, suspended };
}
class EagerOperation final {
public:
struct promise_type {
[[nodiscard]] EagerOperation get_return_object() noexcept;
[[nodiscard]] constexpr std::suspend_never initial_suspend() const noexcept {
return {};
}
[[nodiscard]] constexpr std::suspend_always final_suspend() const noexcept {
return {};
}
constexpr void return_void() const noexcept {}
[[noreturn]] void unhandled_exception() const noexcept {
std::terminate();
}
};
private:
using Handle = std::coroutine_handle<promise_type>;
Handle coroutine_ {};
explicit EagerOperation(Handle coroutine) noexcept
: coroutine_ { coroutine } {}
public:
EagerOperation(const EagerOperation&) = delete;
EagerOperation& operator=(const EagerOperation&) = delete;
EagerOperation(EagerOperation&& other) noexcept
: coroutine_ { std::exchange(other.coroutine_, {}) } {}
EagerOperation& operator=(EagerOperation&&) = delete;
~EagerOperation() {
if (coroutine_) {
coroutine_.destroy();
}
}
};
EagerOperation EagerOperation::promise_type::get_return_object() noexcept {
return EagerOperation {
EagerOperation::Handle::from_promise(*this)
};
}
EagerOperation enqueue_external_work(Scheduler scheduler) {
co_await scheduler.schedule();
}
Task<void> leave_outstanding_work(
Scheduler scheduler,
std::optional<EagerOperation>& operation) {
operation.emplace(enqueue_external_work(std::move(scheduler)));
co_return;
}
Scheduler make_expired_scheduler() {
RunLoop loop {};
return loop.get_scheduler();
}
TEST(CmpRunLoopTest, RunsLazyValueAndVoidTasks) {
RunLoop loop {};
bool started { false };
int value { 0 };
auto task = lazy_value(started);
EXPECT_FALSE(started);
EXPECT_EQ(loop.run(std::move(task)), 42);
EXPECT_TRUE(started);
loop.run(increment(value));
EXPECT_EQ(value, 1);
}
TEST(CmpRunLoopTest, ReturnsMoveOnlyValues) {
RunLoop loop {};
auto value = loop.run(make_move_only_value());
ASSERT_NE(value, nullptr);
EXPECT_EQ(*value, 7);
}
TEST(CmpRunLoopTest, SchedulerIdentityMatchesItsRunLoop) {
RunLoop first {};
RunLoop second {};
EXPECT_EQ(first.get_scheduler(), first.get_scheduler());
EXPECT_NE(first.get_scheduler(), second.get_scheduler());
}
TEST(CmpRunLoopTest, SchedulingResumesOnTheCallingThread) {
RunLoop loop {};
const auto callingThread = std::this_thread::get_id();
auto awaiter = loop.get_scheduler().schedule();
EXPECT_FALSE(awaiter.await_ready());
EXPECT_EQ(loop.run(schedule_once(loop.get_scheduler())), callingThread);
}
TEST(CmpRunLoopTest, SchedulingReturnsFromAnotherThread) {
RunLoop loop {};
std::thread worker {};
const auto callingThread = std::this_thread::get_id();
const auto [workerThread, resumedThread] = loop.run(
leave_and_return(loop.get_scheduler(), worker));
if (worker.joinable()) {
worker.join();
}
EXPECT_NE(workerThread, callingThread);
EXPECT_EQ(resumedThread, callingThread);
}
TEST(CmpRunLoopTest, RootCompletionWakesTheCallingThread) {
RunLoop loop {};
std::thread worker {};
const auto callingThread = std::this_thread::get_id();
const auto completionThread = loop.run(finish_on_new_thread(worker));
if (worker.joinable()) {
worker.join();
}
EXPECT_NE(completionThread, callingThread);
}
TEST(CmpRunLoopTest, PropagatesExceptionAfterScheduling) {
RunLoop loop {};
bool started { false };
EXPECT_THROW(
loop.run(fail_after_scheduling(loop.get_scheduler())),
std::runtime_error);
EXPECT_EQ(loop.run(lazy_value(started)), 42);
EXPECT_TRUE(started);
}
TEST(CmpRunLoopTest, ReusesTheLoopSequentially) {
RunLoop loop {};
bool firstStarted { false };
bool secondStarted { false };
EXPECT_EQ(loop.run(lazy_value(firstStarted)), 42);
EXPECT_EQ(loop.run(lazy_value(secondStarted)), 42);
EXPECT_TRUE(firstStarted);
EXPECT_TRUE(secondStarted);
}
TEST(CmpRunLoopTest, RejectsNestedRunAndRemainsReusable) {
RunLoop loop {};
bool started { false };
EXPECT_THROW(loop.run(run_nested(loop)), std::logic_error);
EXPECT_EQ(loop.run(lazy_value(started)), 42);
EXPECT_TRUE(started);
}
TEST(CmpRunLoopTest, RejectsConcurrentRunAndRemainsReusable) {
RunLoop loop {};
std::coroutine_handle<> continuation {};
std::latch suspended { 1 };
std::exception_ptr driverException {};
std::thread driver { [&] {
try {
loop.run(suspend_manually(continuation, suspended));
} catch (...) {
driverException = std::current_exception();
}
} };
suspended.wait();
ASSERT_TRUE(continuation);
EXPECT_THROW(loop.run(do_nothing()), std::logic_error);
continuation.resume();
driver.join();
EXPECT_FALSE(driverException);
loop.run(do_nothing());
}
TEST(CmpRunLoopTest, RejectsSchedulerWithoutItsActiveRun) {
RunLoop owner {};
RunLoop driver {};
EXPECT_THROW(
driver.run(schedule_once(owner.get_scheduler())),
std::logic_error);
}
TEST(CmpRunLoopTest, RejectsSchedulerAfterRunLoopDestruction) {
RunLoop driver {};
EXPECT_THROW(
driver.run(schedule_once(make_expired_scheduler())),
std::logic_error);
}
TEST(CmpRunLoopTest, RejectsOutstandingWorkAndRemainsReusable) {
RunLoop loop {};
std::optional<EagerOperation> operation {};
EXPECT_THROW(
loop.run(leave_outstanding_work(
loop.get_scheduler(),
operation)),
std::logic_error);
operation.reset();
loop.run(do_nothing());
}
TEST(CmpRunLoopTest, RepeatedSchedulingDoesNotGrowTheStack) {
constexpr int SCHEDULE_COUNT { 100'000 };
RunLoop loop {};
EXPECT_EQ(
loop.run(schedule_many_times(
loop.get_scheduler(),
SCHEDULE_COUNT)),
SCHEDULE_COUNT);
}
} // namespace