-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoroutine_yield.cc
More file actions
158 lines (132 loc) · 2.58 KB
/
coroutine_yield.cc
File metadata and controls
158 lines (132 loc) · 2.58 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include <stdio.h>
#include <queue>
#include <iostream>
#define go(x,y) runtime->newproc(x,y)
class Coroutine;
class Context;
class Runtime;
Coroutine* curr_co;
void* sched_sp;
Runtime* runtime;
class Context
{
public:
int edi;
int esi;
int ebx;
int ebp;
int eip;
};
class Coroutine
{
public:
int id;
char* stack_alloc;
void* stack_base;
void* func;
void* argv;
void* next;
void* esp;
int stat;
Coroutine(int _id,int _size,void* _func,void* _argv)
{
id = _id;
stack_alloc = new char[_size];
stack_base = &stack_alloc[_size];
func = _func;
argv = _argv;
// 初始化堆栈
*((void**)stack_base-1) = _argv;
*((int*)stack_base-2) = 0;
*((int*)stack_base-3) = 0;
*((int*)stack_base-4) = 0;
*((int*)stack_base-5) = 0;
esp = (int*)stack_base-5;
next = _func;
stat = 0;
}
};
extern "C" int corun();
extern "C" void yield();
class Runtime
{
public:
std::queue<Coroutine*> q;
int idx;
Runtime():idx(0)
{
};
void newproc(void (*func)(void*),void* argv);
void enq(Coroutine* c);
Coroutine* deq();
void schedule();
};
void Runtime::newproc(void (*func)(void*), void *argv)
{
Coroutine* c = new Coroutine(this->idx,1024*1024,(void*)func,argv);
this->enq(c);
}
void Runtime::enq(Coroutine *c)
{
this->q.push(c);
}
Coroutine* Runtime::deq()
{
if (this->q.empty())
return nullptr;
else {
Coroutine* c = this->q.front();
this->q.pop();
return c;
}
}
void Runtime::schedule()
{
int ret;
while (true)
{
Coroutine* c = this->deq();
if ( c== nullptr) {
std::cout << "schedule queue empty" << std::endl;
break;
}
curr_co = c;
ret = corun();
if (ret==0)
{
delete c->stack_alloc;
delete c;
} else {
if (c->stat == 0)
c->stat = 1;
this->enq(c);
}
}
}
void foo(void* argv)
{
int* a = (int*)argv;
std::cout << "foo param" << *a << std::endl;
yield();
std::cout << "foo exit" << std::endl;
}
void hi(void* argv)
{
char* a= (char*)argv;
std::cout << "hay" << std::endl;
yield();
std::cout << a << std::endl;
}
int main(int argc,char** argv)
{
runtime = new Runtime();
sched_sp = new char[sizeof(void*)];
// 制造任务
int* fi = new int;
*fi = 100;
go(foo,fi);
char* name=(char*)"liu";
go(hi,name);
runtime->schedule();
return 0;
}