source:
src/examples/coroutine.c
@
148f7290
Last change on this file since 148f7290 was 9129a84, checked in by , 8 years ago | |
---|---|
|
|
File size: 944 bytes |
Rev | Line | |
---|---|---|
[c15b805] | 1 | #include <fstream> |
[0e76cf4f] | 2 | #include <threads> |
[c15b805] | 3 | |
4 | struct Fibonacci { | |
5 | coroutine c; | |
6 | int fn; // used for communication | |
7 | }; | |
8 | ||
9 | void ?{}(Fibonacci* this) { | |
10 | this->fn = 0; | |
11 | } | |
12 | ||
13 | coroutine* this_coroutine(Fibonacci* this) { | |
[9129a84] | 14 | return &this->c; |
[c15b805] | 15 | } |
16 | ||
17 | void co_main(Fibonacci* this) { | |
18 | int fn1, fn2; // retained between resumes | |
19 | this->fn = 0; | |
20 | fn1 = this->fn; | |
[9129a84] | 21 | suspend(); // return to last resume |
[c15b805] | 22 | |
23 | this->fn = 1; | |
24 | fn2 = fn1; | |
25 | fn1 = this->fn; | |
[9129a84] | 26 | suspend(); // return to last resume |
[c15b805] | 27 | |
28 | for ( ;; ) { | |
29 | this->fn = fn1 + fn2; | |
30 | fn2 = fn1; | |
31 | fn1 = this->fn; | |
[9129a84] | 32 | suspend(); // return to last resume |
[c15b805] | 33 | } |
34 | } | |
35 | ||
36 | int next(Fibonacci* this) { | |
37 | resume(this); // transfer to last suspend | |
38 | return this->fn; | |
39 | } | |
40 | ||
[9129a84] | 41 | int main() { |
[c15b805] | 42 | Fibonacci f1, f2; |
43 | for ( int i = 1; i <= 10; i += 1 ) { | |
44 | sout | next(&f1) | ' ' | next(&f2) | endl; | |
45 | } | |
[9129a84] | 46 | |
47 | return 0; | |
[0e76cf4f] | 48 | } |
Note: See TracBrowser
for help on using the repository browser.