-
Notifications
You must be signed in to change notification settings - Fork 160
/
aync_sched.py
108 lines (91 loc) · 3.09 KB
/
aync_sched.py
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
# This is an asynchronous task scheduler based on coroutines
import socket
import select
from collections import deque
class YieldPoint:
def yield_task(self, task):
pass
def resume_task(self, task):
pass
class Scheduler:
def __init__(self):
self.task_cnt = 0
self.tasks = deque()
self.write_wait_tasks = {}
self.read_wait_tasks = {}
def wait_for_write(self, fileno, event, task):
self.write_wait_tasks[fileno] = (event, task)
def wait_for_read(self, fileno, event, task):
self.read_wait_tasks[fileno] = (event, task)
def new_task(self, task):
self.tasks.append((task, None))
self.task_cnt += 1
print "%d tasks"%self.task_cnt
def add_task_back(self, task, data):
self.tasks.append((task, data))
def _poll(self):
r, w, x = select.select(self.read_wait_tasks, self.write_wait_tasks, [])
for r_id in r:
e, task = self.read_wait_tasks.pop(r_id)
e.resume_task(task)
for w_id in w:
e, task = self.write_wait_tasks.pop(w_id)
e.resume_task(task)
def run(self):
while self.task_cnt:
if not self.tasks:
self._poll()
task, data = self.tasks.popleft()
try:
event = task.send(data)
if not isinstance(event, YieldPoint):
raise Exception("Task must yield YieldPoint")
event.yield_task(task)
except StopIteration:
self.task_cnt -= 1
print "%d tasks"%self.task_cnt
# A echo server is implemented as an example
sched = Scheduler()
class ListenYieldPoint(YieldPoint):
def __init__(self, sock):
self.sock = sock
def yield_task(self, task):
sched.wait_for_read(self.sock, self, task)
def resume_task(self, task):
s, _ = self.sock.accept()
sched.add_task_back(task, s)
class RecvYieldPoint(YieldPoint):
def __init__(self, sock):
self.sock = sock
def yield_task(self, task):
sched.wait_for_read(self.sock, self, task)
def resume_task(self, task):
data = self.sock.recv(128)
sched.add_task_back(task, data)
class SendYieldPoint(YieldPoint):
def __init__(self, sock, data):
self.sock = sock
self.data = data
def yield_task(self, task):
sched.wait_for_write(self.sock, self, task)
def resume_task(self, task):
sent = self.sock.send(self.data)
sched.add_task_back(task, sent)
def listener(cnt=5):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("127.0.0.1", 5555))
i = 0
while i<cnt:
sock.listen(5)
new_sock = yield ListenYieldPoint(sock)
print "Accepting Client %d"%i
sched.new_task(handler(new_sock))
i += 1
def handler(sock):
received = yield RecvYieldPoint(sock)
print "RECV:"+received
sent = yield SendYieldPoint(sock, received)
print "SENT:" + str(sent)
sock.close()
sched.new_task(listener())
sched.run()