1 | #include <fstream>
|
---|
2 | #include <threads>
|
---|
3 |
|
---|
4 | struct Fibonacci {
|
---|
5 | int fn; // used for communication
|
---|
6 | covptr_t v;
|
---|
7 | coroutine c;
|
---|
8 | };
|
---|
9 |
|
---|
10 | void co_main(Fibonacci* this);
|
---|
11 | covptr_t* vtable(Fibonacci* this);
|
---|
12 |
|
---|
13 | //GENERATED in proposal for virtuals
|
---|
14 | void co_main_fib(void* this) {
|
---|
15 | co_main( (Fibonacci*) this );
|
---|
16 | }
|
---|
17 |
|
---|
18 | //GENERATED in proposal for virtuals
|
---|
19 | static coVtable_t FibonacciVtable = {
|
---|
20 | co_main_fib,
|
---|
21 | VPTR_OFFSET(Fibonacci, v, c),
|
---|
22 | VPTR_OFFSET(Fibonacci, v, fn)
|
---|
23 | };
|
---|
24 |
|
---|
25 | void ?{}(Fibonacci* this) {
|
---|
26 | this->fn = 0;
|
---|
27 | this->v = &FibonacciVtable; //GENERATED in proposal for virtuals
|
---|
28 | (&this->c) { &this->v };
|
---|
29 | }
|
---|
30 |
|
---|
31 | void co_main(Fibonacci* this) {
|
---|
32 | #ifdef MORE_DEBUG
|
---|
33 | sout | "Starting main of coroutine " | this | endl;
|
---|
34 | sout | "Started from " | this->c.last | endl;
|
---|
35 | #endif
|
---|
36 | int fn1, fn2; // retained between resumes
|
---|
37 | this->fn = 0;
|
---|
38 | fn1 = this->fn;
|
---|
39 | suspend(); // return to last resume
|
---|
40 |
|
---|
41 | this->fn = 1;
|
---|
42 | fn2 = fn1;
|
---|
43 | fn1 = this->fn;
|
---|
44 | suspend(); // return to last resume
|
---|
45 |
|
---|
46 | for ( ;; ) {
|
---|
47 | this->fn = fn1 + fn2;
|
---|
48 | fn2 = fn1;
|
---|
49 | fn1 = this->fn;
|
---|
50 | suspend(); // return to last resume
|
---|
51 | }
|
---|
52 | }
|
---|
53 |
|
---|
54 | int next(Fibonacci* this) {
|
---|
55 | resume(this); // transfer to last suspend
|
---|
56 | return this->fn;
|
---|
57 | }
|
---|
58 |
|
---|
59 | covptr_t* vtable(Fibonacci* this) {
|
---|
60 | return &this->v;
|
---|
61 | }
|
---|
62 |
|
---|
63 | int main() {
|
---|
64 | Fibonacci f1, f2;
|
---|
65 | #ifdef MORE_DEBUG
|
---|
66 | Fibonacci *pf1 = &f1, *pf2 = &f2;
|
---|
67 | coroutine *cf1 = &f1.c, *cf2 = &f2.c;
|
---|
68 | covptr_t *vf1 = vtable(pf1), *vf2 = vtable(pf2);
|
---|
69 | coroutine *cv1 = get_coroutine(vf1), *cv2 = get_coroutine(vf2);
|
---|
70 | Fibonacci *ov1 = (Fibonacci *)get_object(vf1), *ov2 = (Fibonacci *)get_object(vf2);
|
---|
71 |
|
---|
72 | sout | "User coroutines : " | pf1 | ' ' | pf2 | endl;
|
---|
73 | sout | "Coroutine data : " | cf1 | ' ' | cf2 | endl;
|
---|
74 | sout | "Vptr address : " | vf1 | ' ' | vf2 | endl;
|
---|
75 | sout | "Vptr obj data : " | ov1 | ' ' | ov2 | endl;
|
---|
76 | sout | "Vptr cor data : " | cv1 | ' ' | cv2 | endl;
|
---|
77 | #endif
|
---|
78 | for ( int i = 1; i <= 10; i += 1 ) {
|
---|
79 | sout | next(&f1) | ' ' | next(&f2) | endl;
|
---|
80 | }
|
---|
81 |
|
---|
82 | return 0;
|
---|
83 | }
|
---|