forked from ajdavis/coroutines-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path50.py
74 lines (59 loc) · 1.45 KB
/
50.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
from selectors import DefaultSelector, EVENT_WRITE, EVENT_READ
import socket
import time
selector = DefaultSelector()
n_jobs = 0
class Future:
def __init__(self):
self.callback = None
def resolve(self):
self.callback()
def __await__(self):
yield self
class Task:
def __init__(self, coro):
self.coro = coro
self.step()
def step(self):
try:
f = self.coro.send(None)
except StopIteration:
return
f.callback = self.step
async def get(path):
global n_jobs
n_jobs += 1
s = socket.socket()
s.setblocking(False)
try:
s.connect(('localhost', 5000))
except BlockingIOError:
pass
f = Future()
selector.register(s.fileno(), EVENT_WRITE, f)
await f
selector.unregister(s.fileno())
s.send(('GET %s HTTP/1.0\r\n\r\n' % path).encode())
buf = []
while True:
f = Future()
selector.register(s.fileno(), EVENT_READ, f)
await f
selector.unregister(s.fileno())
chunk = s.recv(1000)
if chunk:
buf.append(chunk)
else:
break
# Finished.
print((b''.join(buf)).decode().split('\n')[0])
n_jobs -= 1
start = time.time()
Task(get('/foo'))
Task(get('/bar'))
while n_jobs:
events = selector.select()
for key, mask in events:
future = key.data
future.resolve()
print('took %.2f seconds' % (time.time() - start))