source: src/examples/coroutine.c @ 9129a84

aaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerresolv-newwith_gc
Last change on this file since 9129a84 was 9129a84, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Implemented suspend and resume for coroutines (CtxSw? does nothing)

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