forked from ajdavis/coroutines-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
30.py
47 lines (40 loc) · 1.06 KB
/
30.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
from selectors import DefaultSelector, EVENT_WRITE, EVENT_READ
import socket
import time
selector = DefaultSelector()
n_jobs = 0
def get(path):
global n_jobs
n_jobs += 1
s = socket.socket()
s.setblocking(False)
try:
s.connect(('localhost', 5000))
except BlockingIOError:
pass
selector.register(s.fileno(), EVENT_WRITE, lambda: connected(s, path))
def connected(s, path):
selector.unregister(s.fileno())
s.send(('GET %s HTTP/1.0\r\n\r\n' % path).encode())
buf = []
selector.register(s.fileno(), EVENT_READ, lambda: readable(s, buf))
def readable(s, buf):
global n_jobs
chunk = s.recv(1000)
if chunk:
buf.append(chunk)
else:
# Finished.
selector.unregister(s.fileno())
s.close()
print((b''.join(buf)).decode().split('\n')[0])
n_jobs -= 1
start = time.time()
get('/foo')
get('/bar')
while n_jobs:
events = selector.select()
for key, mask in events:
callback = key.data
callback()
print('took %.2f seconds' % (time.time() - start))