source:
src/tests/coroutine.c
@
75a17f1
Last change on this file since 75a17f1 was 7fbe450, checked in by , 8 years ago | |
---|---|
|
|
File size: 1.7 KB |
Rev | Line | |
---|---|---|
[c15b805] | 1 | #include <fstream> |
[2fc88be] | 2 | #include <coroutines> |
[c15b805] | 3 | |
4 | struct Fibonacci { | |
5 | int fn; // used for communication | |
[5c81105] | 6 | coroutine c; |
[c15b805] | 7 | }; |
8 | ||
[78b3f52] | 9 | void ?{}(Fibonacci* this) { |
10 | this->fn = 0; | |
[80d9e49] | 11 | } |
12 | ||
13 | coroutine* get_coroutine(Fibonacci* this) { | |
14 | return &this->c; | |
[c15b805] | 15 | } |
16 | ||
[7fbe450] | 17 | void main(Fibonacci* this) { |
[d9c44c3] | 18 | #ifdef MORE_DEBUG |
[78b3f52] | 19 | sout | "Starting main of coroutine " | this | endl; |
[5c81105] | 20 | sout | "Started from " | this->c.last | endl; |
[d9c44c3] | 21 | #endif |
[c15b805] | 22 | int fn1, fn2; // retained between resumes |
23 | this->fn = 0; | |
24 | fn1 = this->fn; | |
[9129a84] | 25 | suspend(); // return to last resume |
[c15b805] | 26 | |
27 | this->fn = 1; | |
28 | fn2 = fn1; | |
29 | fn1 = this->fn; | |
[9129a84] | 30 | suspend(); // return to last resume |
[c15b805] | 31 | |
32 | for ( ;; ) { | |
33 | this->fn = fn1 + fn2; | |
34 | fn2 = fn1; | |
35 | fn1 = this->fn; | |
[9129a84] | 36 | suspend(); // return to last resume |
[c15b805] | 37 | } |
38 | } | |
39 | ||
40 | int next(Fibonacci* this) { | |
41 | resume(this); // transfer to last suspend | |
42 | return this->fn; | |
43 | } | |
44 | ||
[9129a84] | 45 | int main() { |
[d9c44c3] | 46 | Fibonacci f1, f2; |
47 | #ifdef MORE_DEBUG | |
[5c81105] | 48 | Fibonacci *pf1 = &f1, *pf2 = &f2; |
49 | coroutine *cf1 = &f1.c, *cf2 = &f2.c; | |
50 | covptr_t *vf1 = vtable(pf1), *vf2 = vtable(pf2); | |
51 | coroutine *cv1 = get_coroutine(vf1), *cv2 = get_coroutine(vf2); | |
52 | Fibonacci *ov1 = (Fibonacci *)get_object(vf1), *ov2 = (Fibonacci *)get_object(vf2); | |
53 | ||
54 | sout | "User coroutines : " | pf1 | ' ' | pf2 | endl; | |
55 | sout | "Coroutine data : " | cf1 | ' ' | cf2 | endl; | |
56 | sout | "Vptr address : " | vf1 | ' ' | vf2 | endl; | |
57 | sout | "Vptr obj data : " | ov1 | ' ' | ov2 | endl; | |
58 | sout | "Vptr cor data : " | cv1 | ' ' | cv2 | endl; | |
[d9c44c3] | 59 | #endif |
[c15b805] | 60 | for ( int i = 1; i <= 10; i += 1 ) { |
[d9c44c3] | 61 | sout | next(&f1) | ' ' | next(&f2) | endl; |
[c15b805] | 62 | } |
[9129a84] | 63 | |
64 | return 0; | |
[0e76cf4f] | 65 | } |
Note: See TracBrowser
for help on using the repository browser.