This repository was archived by the owner on Oct 6, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathtest_libdispatch.cpp
More file actions
1897 lines (1705 loc) · 68.6 KB
/
test_libdispatch.cpp
File metadata and controls
1897 lines (1705 loc) · 68.6 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @author github.com/luncliff (luncliff@gmail.com)
* @brief Personal experiment with libdispatch in Apple platform.
*
* @note clang++ -std=c++2a -stdlib=libc++ -fcoroutines-ts
* @see https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html
* @see https://apple.github.io/swift-corelibs-libdispatch/tutorial/
*/
#define CATCH_CONFIG_RUNNER
#define CATCH_CONFIG_FAST_COMPILE
#include <catch2/catch.hpp>
#include <spdlog/spdlog.h>
// ...
#include <chrono>
#include <dispatch/dispatch.h>
#include <experimental/coroutine>
#include <pthread.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <thread>
#include <unistd.h>
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
using std::experimental::coroutine_handle;
using std::experimental::noop_coroutine;
using std::experimental::suspend_always;
using std::experimental::suspend_never;
using namespace std::chrono_literals;
int main(int argc, char* argv[]) {
spdlog::set_level(spdlog::level::debug);
spdlog::set_pattern("%T %f [%l] %6t %v");
Catch::Session session{};
return session.run(argc, argv);
}
/**
* @see C++ 20 <source_location>
*
* @param loc Location hint to provide more information in the log
* @param exp Exception caught in the coroutine's `unhandled_exception`
*/
void sink_exception(const spdlog::source_loc& loc, std::exception_ptr&& exp) noexcept {
try {
std::rethrow_exception(exp);
} catch (const std::exception& ex) {
spdlog::log(loc, spdlog::level::err, "{}", ex.what());
} catch (...) {
spdlog::critical("unknown exception type");
}
}
/**
* @details `__builtin_coro_resume` fits the signature, but we can't get an address of it
* because it's a compiler intrinsic. Create a simple function for the purpose.
*
* @see dispatch_function_t
*/
void resume_once(void* ptr) noexcept {
auto task = coroutine_handle<void>::from_address(ptr);
if (task.done())
return spdlog::warn("final-suspended coroutine_handle"); // probably because of the logic error
task.resume();
}
/**
* @see C++/WinRT `winrt::fire_and_forget`
*/
struct fire_and_forget final {
struct promise_type final {
constexpr suspend_never initial_suspend() noexcept {
return {};
}
constexpr suspend_never final_suspend() noexcept {
return {};
}
void unhandled_exception() noexcept {
// filename is useless. instead, use the coroutine return type's name
spdlog::source_loc loc{"fire_and_forget", __LINE__, __func__};
sink_exception(loc, std::current_exception());
}
constexpr void return_void() noexcept {
}
fire_and_forget get_return_object() noexcept {
return fire_and_forget{*this};
}
};
explicit fire_and_forget([[maybe_unused]] promise_type&) noexcept {
}
};
struct fire_and_forget_test_case {
/**
* @details Compiler will warn if this function is `noexcept`.
* However, it will be handled by the return type.
* The uncaught exception won't happen here.
*
* @see fire_and_forget::unhandled_exception
*/
static fire_and_forget throw_in_coroutine() noexcept(false) {
co_await suspend_never{};
throw std::runtime_error{__func__};
}
};
TEST_CASE_METHOD(fire_and_forget_test_case, "unhandled exception", "[exception]") {
REQUIRE_NOTHROW(throw_in_coroutine());
}
class paused_action_t final {
public:
class promise_type final {
coroutine_handle<void> next = nullptr; // task that should be continued after `final_suspend`
public:
constexpr suspend_always initial_suspend() noexcept {
return {};
}
auto final_suspend() noexcept {
struct awaitable_t final {
coroutine_handle<void> handle;
public:
constexpr bool await_ready() noexcept {
return false;
}
constexpr coroutine_handle<void> await_suspend(coroutine_handle<void>) noexcept {
return handle;
}
constexpr void await_resume() noexcept {
}
};
return awaitable_t{next ? next : noop_coroutine()};
}
void unhandled_exception() noexcept {
spdlog::source_loc loc{"paused_action_t", __LINE__, __func__};
sink_exception(loc, std::current_exception());
}
constexpr void return_void() noexcept {
}
paused_action_t get_return_object() noexcept {
return paused_action_t{*this};
}
void set_next(coroutine_handle<void> task) noexcept {
next = task;
}
};
private:
coroutine_handle<promise_type> coro;
public:
explicit paused_action_t(promise_type& p) noexcept : coro{coroutine_handle<promise_type>::from_promise(p)} {
}
~paused_action_t() noexcept {
if (coro)
coro.destroy();
}
paused_action_t(const paused_action_t&) = delete;
paused_action_t& operator=(const paused_action_t&) = delete;
paused_action_t(paused_action_t&& rhs) noexcept : coro{rhs.coro} {
rhs.coro = nullptr;
}
paused_action_t& operator=(paused_action_t&& rhs) noexcept {
std::swap(coro, rhs.coro);
return *this;
}
coroutine_handle<void> handle() const noexcept {
return coro;
}
auto operator co_await() noexcept {
struct awaitable_t final {
coroutine_handle<promise_type> action; // handle of the `paused_action_t`
public:
constexpr bool await_ready() const noexcept {
return false;
}
coroutine_handle<void> await_suspend(coroutine_handle<promise_type> coro) noexcept {
action.promise().set_next(coro); // save the task so it can be continued
return action;
}
constexpr void await_resume() const noexcept {
}
};
// chain the next coroutine to given coroutine handle
return awaitable_t{coro};
}
};
static_assert(std::is_copy_constructible_v<paused_action_t> == false);
static_assert(std::is_copy_assignable_v<paused_action_t> == false);
static_assert(std::is_move_constructible_v<paused_action_t> == true);
static_assert(std::is_move_assignable_v<paused_action_t> == true);
struct paused_action_test_case {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
public:
static paused_action_t spawn0() {
co_await suspend_never{};
spdlog::debug("{}", __func__);
co_return;
}
};
TEST_CASE_METHOD(paused_action_test_case, "synchronous dispatch", "[dispatch]") {
paused_action_t action = spawn0();
coroutine_handle<void> coro = action.handle();
REQUIRE(coro);
REQUIRE_FALSE(coro.done());
// these are synchronous operations with a `dispatch_queue_t`
SECTION("dispatch_async_and_wait") {
dispatch_async_and_wait_f(queue, coro.address(), resume_once);
spdlog::debug("dispatch_async_and_wait");
REQUIRE(coro.done());
}
SECTION("dispatch_barrier_async_and_wait") {
dispatch_barrier_async_and_wait_f(queue, coro.address(), resume_once);
spdlog::debug("dispatch_barrier_async_and_wait");
REQUIRE(coro.done());
}
SECTION("dispatch_sync") {
dispatch_sync_f(queue, coro.address(), resume_once);
spdlog::debug("dispatch_sync");
REQUIRE(coro.done());
}
}
/**
* @brief Forward the `coroutine_handle`(job) to `dispatch_queue_t`
* @see dispatch_async_f
* @see https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html
*/
struct queue_awaitable_t final {
dispatch_queue_t queue;
public:
/// @brief true if `queue` is nullptr, resume immediately
constexpr bool await_ready() const noexcept {
return queue == nullptr;
}
/// @see dispatch_async_f
void await_suspend(coroutine_handle<void> coro) noexcept {
dispatch_async_f(queue, coro.address(), resume_once);
}
constexpr void await_resume() const noexcept {
}
};
static_assert(std::is_nothrow_copy_constructible_v<queue_awaitable_t> == true);
static_assert(std::is_nothrow_copy_assignable_v<queue_awaitable_t> == true);
static_assert(std::is_nothrow_move_constructible_v<queue_awaitable_t> == true);
static_assert(std::is_nothrow_move_assignable_v<queue_awaitable_t> == true);
struct queue_awaitable_test_case {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
public:
/**
* @details signal the given semaphore when the coroutine is finished
*/
static fire_and_forget spawn1(dispatch_queue_t queue, dispatch_semaphore_t semaphore) {
co_await queue_awaitable_t{queue};
spdlog::trace("{}", __func__);
dispatch_semaphore_signal(semaphore);
co_return;
}
/**
* @brief With `queue_awaitable_t`, this routine will be resumed by a worker of `dispatch_queue_t`
*/
static paused_action_t spawn2(dispatch_queue_t queue) {
co_await queue_awaitable_t{queue};
spdlog::trace("{}", __func__);
}
/**
* @details spawn3 will await spawn2. By use of paused_action_t,
* `spawn3`'s handle becomes the 'next' of `spawn2`.
* When `spawn2` returns, `spawn3` will be resumed by `end_awaitable_t`.
*/
static paused_action_t spawn3(dispatch_queue_t queue) {
spdlog::trace("{} start", __func__);
co_await spawn2(queue);
spdlog::trace("{} end", __func__);
}
};
TEST_CASE_METHOD(queue_awaitable_test_case, "await and semaphore wait", "[dispatch][semaphore]") {
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
spawn1(queue, semaphore);
// wait for the semaphore signal for 10 ms
const auto d = duration_cast<nanoseconds>(10ms);
const dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, d.count());
REQUIRE(dispatch_semaphore_wait(semaphore, timeout) == 0);
}
TEST_CASE_METHOD(queue_awaitable_test_case, "await and busy wait", "[dispatch]") {
paused_action_t action = spawn3(queue);
coroutine_handle<void> task = action.handle();
REQUIRE_NOTHROW(task.resume());
// spawn2 will be resumed by GCD
while (task.done() == false)
std::this_thread::sleep_for(1ms);
}
TEST_CASE("semaphore lifecycle", "[dispatch][semaphore]") {
SECTION("create, retain, release, release") {
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
dispatch_retain(sem);
dispatch_release(sem);
dispatch_release(sem); // sem is dead.
// dispatch_release(sem); // BAD instruction
}
SECTION("create, release") {
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
dispatch_release(sem); // sem is deamd
// dispatch_release(sem); // BAD instruction
}
}
/// @see https://developer.apple.com/documentation/dispatch/1452955-dispatch_semaphore_create
TEST_CASE("semaphore signal/wait", "[dispatch][semaphore]") {
SECTION("value 0") {
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
dispatch_semaphore_signal(sem);
REQUIRE(dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER) == 0);
REQUIRE(dispatch_semaphore_wait(sem, DISPATCH_TIME_NOW) != 0); // timeout
dispatch_release(sem);
}
SECTION("value 1") {
dispatch_semaphore_t sem = dispatch_semaphore_create(1);
REQUIRE(dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER) == 0);
REQUIRE(dispatch_semaphore_wait(sem, DISPATCH_TIME_NOW) != 0);
// At this point, the semaphore's value is 0.
// `dispatch_release` in this state will lead to EXC_BAD_INSTRUCTION.
// Increase the `value` to that of `dispatch_semaphore_create`
dispatch_semaphore_signal(sem);
dispatch_release(sem);
}
SECTION("value 3") {
dispatch_semaphore_t sem = dispatch_semaphore_create(3);
REQUIRE(dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER) == 0);
REQUIRE(dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER) == 0);
REQUIRE(dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER) == 0);
REQUIRE(dispatch_semaphore_wait(sem, DISPATCH_TIME_NOW) != 0);
// Same as above. But this time the value is 3. We have to signal again and again
dispatch_semaphore_signal(sem);
dispatch_semaphore_signal(sem);
dispatch_semaphore_signal(sem); // back to 3
// if `dispatch_semaphore_signal` is not enough, BAD instruction.
dispatch_release(sem);
}
}
class semaphore_owner_t final {
dispatch_semaphore_t sem;
public:
semaphore_owner_t() noexcept(false) : sem{dispatch_semaphore_create(0)} {
}
explicit semaphore_owner_t(dispatch_semaphore_t handle) noexcept(false) : sem{handle} {
if (handle == nullptr)
throw std::invalid_argument{__func__};
dispatch_retain(sem);
}
~semaphore_owner_t() noexcept {
dispatch_release(sem);
}
semaphore_owner_t(const semaphore_owner_t& rhs) noexcept : semaphore_owner_t{rhs.sem} {
}
semaphore_owner_t(semaphore_owner_t&&) = delete;
semaphore_owner_t& operator=(const semaphore_owner_t&) = delete;
semaphore_owner_t& operator=(semaphore_owner_t&&) = delete;
/// @todo provide a return value?
bool signal() noexcept {
return dispatch_semaphore_signal(sem);
}
[[nodiscard]] bool wait() noexcept {
return dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER) == 0;
}
[[nodiscard]] bool wait_for(std::chrono::nanoseconds duration) noexcept {
return dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, duration.count())) == 0;
}
dispatch_semaphore_t handle() const noexcept {
return sem;
}
};
static_assert(std::is_copy_constructible_v<semaphore_owner_t> == true);
static_assert(std::is_copy_assignable_v<semaphore_owner_t> == false);
static_assert(std::is_move_constructible_v<semaphore_owner_t> == false);
static_assert(std::is_move_assignable_v<semaphore_owner_t> == false);
TEST_CASE("semaphore_owner_t", "[dispatch][semaphore][lifecycle]") {
semaphore_owner_t sem{};
WHEN("untouched") {
// do nothing with the instance
}
WHEN("copy construction") {
semaphore_owner_t sem2{sem};
}
GIVEN("signaled") {
REQUIRE_NOTHROW(sem.signal());
WHEN("wait/wait_for") {
REQUIRE(sem.wait());
REQUIRE_FALSE(sem.wait_for(1s)); // already consumed by previous wait
}
WHEN("wait_for/wait_for") {
REQUIRE(sem.wait_for(1s));
REQUIRE_FALSE(sem.wait_for(0s)); // already consumed by previous wait
}
}
GIVEN("not-signaled")
WHEN("wait_for") {
REQUIRE_FALSE(sem.wait_for(0s));
}
}
/**
* @brief A coroutine return type which supports wait/wait_for with `dispatch_semaphore_t`
* @details When this type is used, the coroutine's first argument must be a valid `dispatch_semaphore_t`
*/
class semaphore_action_t final {
public:
class promise_type final {
friend class semaphore_action_t;
dispatch_semaphore_t semaphore;
public:
/// @note This signature is for Clang compiler. defined(__clang__)
template <typename... Args>
promise_type(dispatch_semaphore_t handle, [[maybe_unused]] Args&&...) noexcept(false) : semaphore{handle} {
}
/// @note This signature is for MSVC. defined(_MSC_VER)
promise_type() noexcept = default;
promise_type(const promise_type&) = delete;
promise_type(promise_type&&) = delete;
promise_type& operator=(const promise_type&) = delete;
promise_type& operator=(promise_type&&) = delete;
suspend_never initial_suspend() noexcept {
dispatch_retain(semaphore);
return {};
}
suspend_never final_suspend() noexcept {
dispatch_release(semaphore);
return {};
}
void unhandled_exception() noexcept {
spdlog::source_loc loc{"semaphore_action_t", __LINE__, __func__};
sink_exception(loc, std::current_exception());
}
void return_void() noexcept {
dispatch_semaphore_signal(semaphore);
}
semaphore_action_t get_return_object() noexcept {
return semaphore_action_t{*this};
}
};
private:
semaphore_owner_t sem;
private:
/// @note change the `promise_type`'s handle before `initial_suspend`
explicit semaphore_action_t(promise_type& p) noexcept
// We have to share the semaphore between coroutine frame and return instance.
// If `promise_type` is created with multiple arguments, the handle won't be nullptr.
: sem{p.semaphore ? p.semaphore : dispatch_semaphore_create(0)} {
// When the compiler default-constructed the `promise_type`, its semaphore will be nullptr.
if (p.semaphore == nullptr) {
// Share a newly created one
p.semaphore = sem.handle();
// We used dispatch_semaphore_create above.
// The reference count is higher than what we want
dispatch_release(p.semaphore);
}
}
public:
semaphore_action_t(const semaphore_action_t&) noexcept = default;
semaphore_action_t(semaphore_action_t&&) noexcept = delete;
semaphore_action_t& operator=(const semaphore_action_t&) noexcept = delete;
semaphore_action_t& operator=(semaphore_action_t&&) noexcept = delete;
[[nodiscard]] bool wait() noexcept {
return sem.wait();
}
[[nodiscard]] bool wait_for(std::chrono::nanoseconds duration) noexcept {
return sem.wait_for(duration);
}
};
static_assert(std::is_copy_constructible_v<semaphore_action_t> == true);
static_assert(std::is_copy_assignable_v<semaphore_action_t> == false);
static_assert(std::is_move_constructible_v<semaphore_action_t> == false);
static_assert(std::is_move_assignable_v<semaphore_action_t> == false);
struct semaphore_action_test_case {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
static fire_and_forget sleep_and_signal(dispatch_queue_t queue, //
dispatch_semaphore_t handle, std::chrono::seconds duration) {
semaphore_owner_t sem{handle}; // guarantee life of the semaphore with retain/release
co_await queue_awaitable_t{queue};
std::this_thread::sleep_for(duration);
spdlog::debug("signal: {}", (void*)sem.handle());
sem.signal(); // == dispatch_semaphore_signal
};
/// @note the order of the arguments
static semaphore_action_t sleep_and_return(dispatch_semaphore_t sem, dispatch_queue_t queue,
std::chrono::seconds duration) {
co_await queue_awaitable_t{queue};
std::this_thread::sleep_for(duration);
spdlog::debug("signal: {}", (void*)sem);
co_return; // `promise_type::return_void` will signal the semaphore
};
};
TEST_CASE_METHOD(semaphore_action_test_case, "launch and wait", "[dispatch][semaphore]") {
semaphore_action_t action = sleep_and_return(dispatch_semaphore_create(0), queue, 1s);
spdlog::debug("wait: {}", "begin");
REQUIRE_FALSE(action.wait_for(0s)); // there is a sleep, so this must fail
REQUIRE(action.wait());
spdlog::debug("wait: {}", "end");
}
TEST_CASE_METHOD(semaphore_action_test_case, "wait first action", "[dispatch][semaphore]") {
auto cleanup = [](dispatch_semaphore_t handle) {
spdlog::debug("wait: {}", (void*)handle);
// ensure all coroutines are finished in this section
std::this_thread::sleep_for(3s);
};
semaphore_owner_t sem{};
SECTION("manual") {
sleep_and_signal(queue, sem.handle(), 1s);
sleep_and_signal(queue, sem.handle(), 2s);
sleep_and_signal(queue, sem.handle(), 3s);
REQUIRE(sem.wait());
cleanup(sem.handle());
}
SECTION("signal with co_return") {
sleep_and_return(sem.handle(), queue, 1s);
sleep_and_return(sem.handle(), queue, 2s);
sleep_and_return(sem.handle(), queue, 3s);
REQUIRE(sem.wait());
cleanup(sem.handle());
}
}
struct group_test_case {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
public:
group_test_case() {
REQUIRE(group); // dispatch_group_create may return NULL
}
~group_test_case() {
dispatch_release(group);
}
static paused_action_t leave_when_return(dispatch_group_t group) {
co_await suspend_never{};
spdlog::debug("leave_when_return");
co_return dispatch_group_leave(group);
}
static paused_action_t wait_and_signal(dispatch_group_t group, dispatch_semaphore_t sem) {
co_await suspend_never{};
spdlog::debug("wait_and_signal");
auto ec = dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
spdlog::debug("wait_and_signal: {}", ec);
dispatch_semaphore_signal(sem);
co_return;
}
};
TEST_CASE_METHOD(group_test_case, "dispatch_group lifecycle", "[dispatch][group]") {
SECTION("release without retain") {
std::this_thread::sleep_for(10ms);
}
SECTION("additional retain, release") {
dispatch_retain(group);
std::this_thread::sleep_for(10ms);
dispatch_release(group);
}
}
TEST_CASE_METHOD(group_test_case, "dispatch_async_f + dispatch_group_async_f", "[dispatch][group]") {
semaphore_owner_t sem{};
paused_action_t t1 = leave_when_return(group);
dispatch_group_enter(group); // group reference count == 1
REQUIRE_FALSE(t1.handle().done());
paused_action_t t2 = leave_when_return(group);
dispatch_group_enter(group); // group reference count == 2
REQUIRE_FALSE(t2.handle().done());
paused_action_t t3 = wait_and_signal(group, sem.handle());
dispatch_async_f(queue, t3.handle().address(), resume_once); // t3 will wait until the group is done
dispatch_group_async_f(group, queue, t1.handle().address(), resume_once); // --> dispatch_group_wait
dispatch_group_async_f(group, queue, t2.handle().address(), resume_once); // --> dispatch_group_wait
REQUIRE(sem.wait_for(5s));
REQUIRE(t1.handle().done());
REQUIRE(t2.handle().done());
REQUIRE(t3.handle().done());
}
/**
* @see dispatch_group_notify_f
*/
struct group_awaitable_t final {
dispatch_group_t group;
dispatch_queue_t queue;
public:
[[nodiscard]] bool await_ready() const noexcept {
return dispatch_group_wait(group, DISPATCH_TIME_NOW) == 0;
}
/// @see dispatch_group_notify_f
void await_suspend(coroutine_handle<void> coro) const noexcept {
return dispatch_group_notify_f(group, queue, coro.address(), resume_once);
}
constexpr dispatch_group_t await_resume() const noexcept {
return group;
}
};
class group_action_t final {
public:
class promise_type final {
dispatch_group_t group;
public:
// explicit promise_type(dispatch_group_t group) noexcept(false) : group{group} {
// if (group == nullptr)
// throw std::invalid_argument{__func__};
// dispatch_retain(group);
// }
template <typename... Args>
promise_type(dispatch_group_t group, [[maybe_unused]] Args&&...) noexcept(false) : group{group} {
if (group == nullptr)
throw std::invalid_argument{__func__};
dispatch_retain(group);
}
~promise_type() {
dispatch_release(group);
}
promise_type(const promise_type&) = delete;
promise_type(promise_type&&) = delete;
promise_type& operator=(const promise_type&) = delete;
promise_type& operator=(promise_type&&) = delete;
suspend_always initial_suspend() noexcept {
dispatch_group_enter(group);
return {};
}
suspend_never final_suspend() noexcept {
dispatch_group_leave(group);
return {};
}
void unhandled_exception() noexcept {
spdlog::source_loc loc{"group_action_t", __LINE__, __func__};
sink_exception(loc, std::current_exception());
}
constexpr void return_void() noexcept {
}
group_action_t get_return_object() noexcept {
return group_action_t{*this, group};
}
};
private:
coroutine_handle<promise_type> coro;
dispatch_group_t const group;
public:
/**
* @note `dispatch_group_async_f` retains the group. so this type won't modify reference count of it
* @see run_on
*/
group_action_t(promise_type& p, dispatch_group_t group) noexcept
: coro{coroutine_handle<promise_type>::from_promise(p)}, group{group} {
}
group_action_t(const group_action_t&) = delete;
group_action_t(group_action_t&&) noexcept = default;
group_action_t& operator=(const group_action_t&) = delete;
group_action_t& operator=(group_action_t&&) = delete;
/**
* @brief Schedule the initial-suspended coroutine to the given queue
* @note Using this function more than 1 will cause undefined behavior
* @see dispatch_group_async_f
* @param queue destination queue to schedule current coroutine handle
*/
void run_on(dispatch_queue_t queue) noexcept {
dispatch_group_async_f(group, queue, coro.address(), resume_once);
coro = nullptr; // suspend_never in `promise_type::final_suspend`
}
};
static_assert(std::is_copy_constructible_v<group_action_t> == false);
static_assert(std::is_copy_assignable_v<group_action_t> == false);
static_assert(std::is_move_constructible_v<group_action_t> == true);
static_assert(std::is_move_assignable_v<group_action_t> == false);
struct group_action_test_case : public group_test_case {
public:
static group_action_t print_and_return([[maybe_unused]] dispatch_group_t, uint32_t line) {
co_await suspend_never{};
co_return spdlog::debug("print_and_return: {}", line);
}
static fire_and_forget wait_and_signal2(dispatch_group_t group, dispatch_queue_t queue, dispatch_semaphore_t sem) {
spdlog::debug("wait_and_signal2");
co_await group_awaitable_t{group, queue};
spdlog::debug("wait_and_signal2: awake");
dispatch_semaphore_signal(sem);
}
static group_action_t subtask1(dispatch_group_t, dispatch_queue_t queue) {
co_await queue_awaitable_t{queue};
spdlog::debug("subtask");
}
static semaphore_action_t wait_and_signal3(dispatch_semaphore_t, dispatch_group_t group, dispatch_queue_t queue) {
uint32_t count = 10;
while (count--) {
group_action_t action = subtask1(group, queue);
action.run_on(queue);
}
co_await group_awaitable_t{group, queue};
co_return spdlog::debug("wait_and_signal3");
}
};
TEST_CASE_METHOD(group_action_test_case, "wait group with dispatch_async_f", "[dispatch][group]") {
semaphore_owner_t sem{};
group_action_t action1 = print_and_return(group, __LINE__); // reference count == 1
group_action_t action2 = print_and_return(group, __LINE__); // reference count == 2
group_action_t action3 = print_and_return(group, __LINE__); // reference count == 3
// it will wait (synchronously) until the group is done
paused_action_t waiter = wait_and_signal(group, sem.handle());
dispatch_async_f(queue, waiter.handle().address(), resume_once);
action1.run_on(queue); // --> dispatch_group_wait
action2.run_on(queue); // --> dispatch_group_wait
action3.run_on(queue); // --> dispatch_group_wait
REQUIRE(sem.wait_for(5s));
REQUIRE(waiter.handle().done());
}
TEST_CASE_METHOD(group_action_test_case, "wait group with dispatch_group_notify_f", "[dispatch][group]") {
semaphore_owner_t sem{};
group_action_t action1 = print_and_return(group, __LINE__); // reference count == 1
group_action_t action2 = print_and_return(group, __LINE__); // reference count == 2
group_action_t action3 = print_and_return(group, __LINE__); // reference count == 3
WHEN("await before schedules") {
// wait until the group is completed
wait_and_signal2(group, queue, sem.handle());
action1.run_on(queue); // --> dispatch_group_wait
action2.run_on(queue); // --> dispatch_group_wait
action3.run_on(queue); // --> dispatch_group_wait
REQUIRE(sem.wait());
}
WHEN("schedules before await") {
action1.run_on(queue); // --> dispatch_group_wait
action2.run_on(queue); // --> dispatch_group_wait
action3.run_on(queue); // --> dispatch_group_wait
std::this_thread::sleep_for(1s);
// the group is already completed
wait_and_signal2(group, queue, sem.handle());
REQUIRE(sem.wait());
}
}
TEST_CASE_METHOD(group_action_test_case, "wait group witt group_awaitable_t", "[dispatch][group]") {
semaphore_action_t action = wait_and_signal3(dispatch_semaphore_create(0), group, queue);
REQUIRE(action.wait());
}
struct timer_source_test_case {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = nullptr;
std::atomic_uint32_t num_update = 0;
std::atomic_uint32_t num_cancel = 0;
public:
timer_source_test_case() : timer{dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)} {
REQUIRE(timer);
dispatch_retain(timer);
}
~timer_source_test_case() {
if (timer == nullptr)
return;
dispatch_release(timer);
}
public:
static void on_timed_update(timer_source_test_case& t) noexcept {
++t.num_update;
spdlog::debug("timer callback: {} {}", (void*)t.timer, t.num_update);
}
static void on_timed_canceled(timer_source_test_case& t) noexcept {
++t.num_cancel;
spdlog::debug("timer canceled: {} {}", (void*)t.timer, t.num_cancel);
dispatch_suspend(t.timer);
}
void reset_handlers() noexcept {
dispatch_set_context(timer, this);
dispatch_source_set_event_handler_f(timer, reinterpret_cast<dispatch_function_t>(on_timed_update));
dispatch_source_set_cancel_handler_f(timer, reinterpret_cast<dispatch_function_t>(on_timed_canceled));
}
};
SCENARIO_METHOD(timer_source_test_case, "dispatch timer", "[dispatch][timer]") {
dispatch_set_context(timer, this);
GIVEN("cancel handler") {
dispatch_source_set_cancel_handler_f(timer, reinterpret_cast<dispatch_function_t>(on_timed_canceled));
WHEN("cancel without resume") {
dispatch_source_cancel(timer);
// it's canced in suspended state
// dispatch_sync_f(queue, noop_coroutine().address(), resume_once);
std::this_thread::sleep_for(10ms);
REQUIRE(num_cancel == 0);
}
WHEN("cancel with resume") {
dispatch_resume(timer);
dispatch_source_cancel(timer);
std::this_thread::sleep_for(10ms);
REQUIRE(num_cancel == 1);
}
}
GIVEN("event handler") {
const auto interval = duration_cast<nanoseconds>(20ms);
dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, interval.count() / 2), interval.count(),
(500us).count());
dispatch_source_set_event_handler_f(timer, reinterpret_cast<dispatch_function_t>(on_timed_update));
dispatch_resume(timer);
std::this_thread::sleep_for(interval);
REQUIRE(num_update.load() == 1);
WHEN("release") {
auto source = timer;
dispatch_release(timer);
timer = nullptr;
std::this_thread::sleep_for(interval);
REQUIRE(num_update.load() == 2); // timer still works
dispatch_source_cancel(source); // make sure no more invoke
}
WHEN("cancel") {
dispatch_source_cancel(timer);
std::this_thread::sleep_for(interval);
REQUIRE(num_update.load() == 1); // no increase
}
WHEN("suspend without cancel") {
dispatch_suspend(timer);
std::this_thread::sleep_for(interval);
REQUIRE(num_update.load() == 1); // no increase
}
}
}
/**
* @brief Hold a timer and expose some shortcuts to start/suspend/cancel
* @see dispatch_source_create
* @see DISPATCH_SOURCE_TYPE_TIMER
*/
class timer_owner_t final {
dispatch_source_t source;
public:
explicit timer_owner_t(dispatch_source_t timer) noexcept(false) : source{timer} {
if (source == nullptr)
throw std::runtime_error{"dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER)"};
dispatch_retain(source);
}
explicit timer_owner_t(dispatch_queue_t queue) noexcept(false)
: timer_owner_t{dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)} {
}
~timer_owner_t() noexcept {
dispatch_release(source);
}
timer_owner_t(const timer_owner_t&) = delete;
timer_owner_t& operator=(const timer_owner_t&) = delete;
timer_owner_t(timer_owner_t&&) = delete;
timer_owner_t& operator=(timer_owner_t&&) = delete;
dispatch_source_t handle() const noexcept {
return source;
}
void set(void* context, dispatch_function_t on_event, dispatch_function_t on_cancel) noexcept {
dispatch_set_context(source, context);
dispatch_source_set_event_handler_f(source, on_event);
dispatch_source_set_cancel_handler_f(source, on_cancel);
}
void start(std::chrono::nanoseconds interval, dispatch_time_t start) noexcept {
dispatch_source_set_timer(source, start, interval.count(), duration_cast<nanoseconds>(500us).count());
return dispatch_resume(source);
}
/**
* @param context context of dispatch_source_t to change
* @param on_cancel cancel handler of dispatch_source to change
* @return true if the timer is canceled
*/
bool cancel(void* context = nullptr, dispatch_function_t on_cancel = nullptr) noexcept {
if (context)
dispatch_set_context(source, context);
if (on_cancel)
dispatch_source_set_cancel_handler_f(source, on_cancel);
// cancel after check
if (dispatch_source_testcancel(source) != 0)
return false;
dispatch_source_cancel(source);
return true;
}
void suspend() noexcept {
dispatch_suspend(source);
}
};
struct timer_owner_test_case {
std::atomic<uint32_t> num_update = 0;
std::atomic<uint32_t> num_cancel = 0;
public:
static void on_timer_cancel(timer_owner_test_case& info) noexcept {
++info.num_cancel;
}
static void on_timer_event(timer_owner_test_case& info) noexcept {
++info.num_update;
}
};
TEST_CASE_METHOD(timer_owner_test_case, "timer_owner_t", "[dispatch][timer]") {
timer_owner_t timer{dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)};
timer.set(this, //
reinterpret_cast<dispatch_function_t>(on_timer_event), // num_update+1
reinterpret_cast<dispatch_function_t>(on_timer_cancel) // num_cancel+1 and suspend
);
GIVEN("untouched") {
WHEN("suspend once") {
timer.suspend();
REQUIRE(num_update == 0);
}
WHEN("cancel") {
// not resumed. so we no cancel effect
timer.cancel();
std::this_thread::sleep_for(30ms);
REQUIRE(num_cancel == 0);
}
}
GIVEN("started") {
timer.start(20ms, DISPATCH_TIME_NOW);
std::this_thread::sleep_for(15ms);
WHEN("suspend once") {
timer.suspend();
REQUIRE(num_update == 1);
REQUIRE(num_cancel == 0);
}
WHEN("cancel") {
timer.cancel();
// give a short time to run the handler with queue
std::this_thread::sleep_for(40ms); // give more than twice of start interval
REQUIRE(num_update < 2);
REQUIRE(num_cancel == 1);
}
}
GIVEN("suspended") {
timer.start(10ms, DISPATCH_TIME_NOW);
std::this_thread::sleep_for(15ms);
timer.suspend();
REQUIRE(num_update == 2);
REQUIRE(num_cancel == 0);
WHEN("start again") {
timer.start(20ms, DISPATCH_TIME_NOW);
std::this_thread::sleep_for(10ms);
timer.suspend();
REQUIRE(num_update == 3);
}
WHEN("cancel") {
// not resumed. so no cancel effect
timer.cancel();
std::this_thread::sleep_for(40ms); // give more than twice of start interval
REQUIRE(num_update == 2);
REQUIRE(num_cancel == 0);
}
}
}
/**
* @brief Resume the given task in nanosecond interval
*/