source:
src/examples/coroutine.c
@
e4745d7a
Last change on this file since e4745d7a was 78b3f52, checked in by , 8 years ago | |
---|---|
|
|
File size: 1.5 KB |
Rev | Line | |
---|---|---|
[c15b805] | 1 | #include <fstream> |
[0e76cf4f] | 2 | #include <threads> |
[c15b805] | 3 | |
4 | struct Fibonacci { | |
5 | coroutine c; | |
[78b3f52] | 6 | coVtable v; |
[c15b805] | 7 | int fn; // used for communication |
8 | }; | |
9 | ||
[78b3f52] | 10 | coroutine* this_coroutine(Fibonacci* this); |
11 | void co_main(Fibonacci* this); | |
12 | coVtable* vtable(Fibonacci* this); | |
13 | ||
14 | void co_main_fib(void* this) { | |
15 | co_main( (Fibonacci*) this ); | |
[c15b805] | 16 | } |
17 | ||
[78b3f52] | 18 | coroutine* this_coroutine_fib(void* this) { |
19 | return this_coroutine( (Fibonacci*) this); | |
20 | } | |
21 | ||
22 | void ?{}(Fibonacci* this) { | |
23 | this->fn = 0; | |
24 | this->v.main = co_main_fib; | |
25 | this->v.this_coroutine = this_coroutine_fib; | |
26 | start(this); | |
[c15b805] | 27 | } |
28 | ||
29 | void co_main(Fibonacci* this) { | |
[78b3f52] | 30 | sout | "Starting main of coroutine " | this | endl; |
31 | sout | "Started from " | this_coroutine(this)->last | endl; | |
[c15b805] | 32 | int fn1, fn2; // retained between resumes |
33 | this->fn = 0; | |
34 | fn1 = this->fn; | |
[9129a84] | 35 | suspend(); // return to last resume |
[c15b805] | 36 | |
37 | this->fn = 1; | |
38 | fn2 = fn1; | |
39 | fn1 = this->fn; | |
[9129a84] | 40 | suspend(); // return to last resume |
[c15b805] | 41 | |
42 | for ( ;; ) { | |
43 | this->fn = fn1 + fn2; | |
44 | fn2 = fn1; | |
45 | fn1 = this->fn; | |
[9129a84] | 46 | suspend(); // return to last resume |
[c15b805] | 47 | } |
48 | } | |
49 | ||
50 | int next(Fibonacci* this) { | |
51 | resume(this); // transfer to last suspend | |
52 | return this->fn; | |
53 | } | |
54 | ||
[78b3f52] | 55 | coroutine* this_coroutine(Fibonacci* this) { |
56 | return &this->c; | |
57 | } | |
58 | ||
59 | coVtable* vtable(Fibonacci* this) { | |
60 | return &this->v; | |
61 | } | |
62 | ||
[9129a84] | 63 | int main() { |
[78b3f52] | 64 | Fibonacci f1; |
65 | sout | "User coroutine : " | &f1 | endl; | |
[c15b805] | 66 | for ( int i = 1; i <= 10; i += 1 ) { |
[78b3f52] | 67 | sout | next(&f1) | endl; |
[c15b805] | 68 | } |
[9129a84] | 69 | |
70 | return 0; | |
[0e76cf4f] | 71 | } |
Note: See TracBrowser
for help on using the repository browser.