-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest.cpp
More file actions
92 lines (78 loc) · 2.47 KB
/
test.cpp
File metadata and controls
92 lines (78 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//Suppose we rent the cpu time in a strange old super computer and costing no more than 256 "clock" each time for example.
//So computing is enabled only after allowed and we need to divide our computing task into several one.
//This is an example to simulate the IO operation that only enabled after select or (e)poll result.
//Now we want to get the nth fibonacci numbers: 0,1,1,2,3,5,8,13,21,34,55,89....
//But we implement a fool recursive algorithm to get the result.
//Try to divide the computing task to several simpler one to be finished in the old super computer.
#include <stdio.h>
#include <stdlib.h>
#include <stack>
#include "cort_proto.h"
std::stack<cort_proto*> scheduler_list;
unsigned char the_clock = 1;
void push_work(cort_proto* arg){
scheduler_list.push(arg);
}
void pop_work(){
scheduler_list.pop();
}
bool pop_execute_work(){
if(scheduler_list.empty()){
return false;
}
cort_proto* p = scheduler_list.top();
scheduler_list.pop();
p->resume();
if(scheduler_list.empty()){
return false;
}
return true;
}
struct fibonacci_cort;
struct fibonacci_cort : public cort_proto{
fibonacci_cort *corts[2];
int n;
int result;
//You can define anything.
~fibonacci_cort(){
}
fibonacci_cort(int input): n(input){
}
CO_BEGIN(fibonacci_cort)
if(++the_clock == 0){ //Oh you are not enabled to work now.
push_work(this);
CO_AWAIT_AGAIN();
}
if(n < 2){
result = n;
CO_RETURN();
}
corts[0] = new fibonacci_cort(n-1);
corts[1] = new fibonacci_cort(n-2);
//They may cost much time so we should wait their result.
CO_AWAIT_ALL(corts[0], corts[1]); //You can place no more than ten corts for CO_AWAIT_ALL.
//CO_AWAIT_RANGE(corts, corts+2); //Or using forward iterator of coroutine pointer for variate count.
if(++the_clock == 0){ //Oh you are not enabled to work now.
push_work(this);
CO_AWAIT_AGAIN();
}
result = corts[0]->result + corts[1]->result;
delete corts[0];
delete corts[1];
CO_END(fibonacci_cort)
};
int main(int argc, char* argv[]){
if(argc <= 1){
argc = 18;
}
else{
argc = atoi(argv[1]);
}
fibonacci_cort main_task(argc);
main_task.start();
while(pop_execute_work()){
//sleep(1);
}
printf("%d\n", main_task.result);
return 0;
}