source: src/tests/coroutine.c@ 2cd0434

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 2cd0434 was 5c81105, checked in by Thierry Delisle <tdelisle@…>, 9 years ago

cleaned-up coroutines code to no longer need a manual start

  • Property mode set to 100644
File size: 2.1 KB
RevLine 
[c15b805]1#include <fstream>
[0e76cf4f]2#include <threads>
[c15b805]3
4struct Fibonacci {
5 int fn; // used for communication
[5c81105]6 covptr_t v;
7 coroutine c;
[c15b805]8};
9
[78b3f52]10void co_main(Fibonacci* this);
[5c81105]11covptr_t* vtable(Fibonacci* this);
[78b3f52]12
[5c81105]13//GENERATED in proposal for virtuals
[78b3f52]14void co_main_fib(void* this) {
15 co_main( (Fibonacci*) this );
[c15b805]16}
17
[5c81105]18//GENERATED in proposal for virtuals
19static coVtable_t FibonacciVtable = {
20 co_main_fib,
21 VPTR_OFFSET(Fibonacci, v, c),
22 VPTR_OFFSET(Fibonacci, v, fn)
23};
[78b3f52]24
25void ?{}(Fibonacci* this) {
26 this->fn = 0;
[5c81105]27 this->v = &FibonacciVtable; //GENERATED in proposal for virtuals
28 (&this->c) { &this->v };
[c15b805]29}
30
31void co_main(Fibonacci* this) {
[d9c44c3]32#ifdef MORE_DEBUG
[78b3f52]33 sout | "Starting main of coroutine " | this | endl;
[5c81105]34 sout | "Started from " | this->c.last | endl;
[d9c44c3]35#endif
[c15b805]36 int fn1, fn2; // retained between resumes
37 this->fn = 0;
38 fn1 = this->fn;
[9129a84]39 suspend(); // return to last resume
[c15b805]40
41 this->fn = 1;
42 fn2 = fn1;
43 fn1 = this->fn;
[9129a84]44 suspend(); // return to last resume
[c15b805]45
46 for ( ;; ) {
47 this->fn = fn1 + fn2;
48 fn2 = fn1;
49 fn1 = this->fn;
[9129a84]50 suspend(); // return to last resume
[c15b805]51 }
52}
53
54int next(Fibonacci* this) {
55 resume(this); // transfer to last suspend
56 return this->fn;
57}
58
[5c81105]59covptr_t* vtable(Fibonacci* this) {
[78b3f52]60 return &this->v;
61}
62
[9129a84]63int main() {
[d9c44c3]64 Fibonacci f1, f2;
65#ifdef MORE_DEBUG
[5c81105]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;
[d9c44c3]77#endif
[c15b805]78 for ( int i = 1; i <= 10; i += 1 ) {
[d9c44c3]79 sout | next(&f1) | ' ' | next(&f2) | endl;
[c15b805]80 }
[9129a84]81
82 return 0;
[0e76cf4f]83}
Note: See TracBrowser for help on using the repository browser.