source: doc/papers/concurrency/c++-cor/counter.cpp@ 79b018f3

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 79b018f3 was be3416d, checked in by tdelisle <tdelisle@…>, 7 years ago

Added more examples of c++20 coroutines

  • Property mode set to 100644
File size: 1.3 KB
Line 
1#include "base.hpp"
2
3struct counter_cor {
4 struct promise_type {
5 counter_cor get_return_object() {
6 return counter_cor(std::experimental::coroutine_handle<promise_type>::from_promise(*this));
7 }
8
9 auto initial_suspend() { return suspend_never(); }
10 auto final_suspend() { return suspend_never(); }
11
12 void return_void() {}
13
14 void unhandled_exception() {}
15 };
16
17 std::experimental::coroutine_handle<promise_type> _coroutine = nullptr;
18
19 explicit counter_cor(std::experimental::coroutine_handle<promise_type> coroutine)
20 : _coroutine(coroutine)
21 {}
22
23 ~counter_cor() {
24 if(_coroutine) { _coroutine.destroy(); }
25 }
26
27 counter_cor() = default;
28 counter_cor(counter_cor const &) = delete;
29 counter_cor& operator=(counter_cor const &) = delete;
30
31 counter_cor(counter_cor&& other) {
32 std::swap(_coroutine, other._coroutine);
33 }
34
35 counter_cor& operator=(counter_cor&& other) {
36 if(&other != this) {
37 _coroutine = other._coroutine;
38 other._coroutine = nullptr;
39 }
40 return *this;
41 }
42
43 void resume() { _coroutine.resume(); }
44};
45
46counter_cor counter() {
47 std::cout << "Counter: called\n";
48 for(unsigned i = 1;; i++) {
49 co_await suspend_always{};
50 std::cout << "Counter: Resumed " << i << " time(s)\n";
51 }
52}
53
54int main() {
55 std::cout << "Main: calling counter\n";
56 auto c = counter();
57 std::cout << "Main: resumes\n";
58 c.resume();
59 c.resume();
60 std::cout << "Main: done\n";
61}
Note: See TracBrowser for help on using the repository browser.