Skip to content

Commit 80ecd3b

Browse files
author
Paul Sokolovsky
committed
asyncio: Initial prototype implementation.
1 parent 84f3cbb commit 80ecd3b

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

asyncio/asyncio.py

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import time
2+
import heapq
3+
4+
5+
def coroutine(f):
6+
return f
7+
8+
9+
def get_event_loop():
10+
return EventLoop()
11+
12+
13+
class EventLoop:
14+
15+
def __init__(self):
16+
self.q = []
17+
self.cnt = 0
18+
19+
def time(self):
20+
return time.time()
21+
22+
def call_soon(self, callback, *args):
23+
self.call_at(0, callback, *args)
24+
25+
def call_later(self, delay, callback, *args):
26+
self.call_at(self.time() + delay, callback, *args)
27+
28+
def call_at(self, time, callback, *args):
29+
# self.q.append((callback, args))
30+
# self.cnt is workaround per heapq docs
31+
# print("Scheduling", (time, self.cnt, callback, args))
32+
heapq.heappush(self.q, (time, self.cnt, callback, args))
33+
# print(self.q)
34+
self.cnt += 1
35+
36+
# def run_forever(self):
37+
# while self.q:
38+
# c = self.q.pop(0)
39+
# c[0](*c[1])
40+
41+
def run_forever(self):
42+
while self.q:
43+
# t, cnt, cb, args = self.q.pop(0)
44+
t, cnt, cb, args = heapq.heappop(self.q)
45+
tnow = self.time()
46+
delay = t - tnow
47+
if delay > 0:
48+
# print("Sleeping for:", delay)
49+
time.sleep(delay)
50+
delay = 0
51+
try:
52+
ret = next(cb)
53+
# print("ret:", ret)
54+
if isinstance(ret, Sleep):
55+
delay = ret.args[0]
56+
except StopIteration as e:
57+
print(c, "finished")
58+
continue
59+
#self.q.append(c)
60+
self.call_later(delay, cb, *args)
61+
62+
def run_until_complete(self, coro):
63+
val = None
64+
while True:
65+
try:
66+
ret = coro.send(val)
67+
except StopIteration as e:
68+
print(e)
69+
break
70+
print("ret:", ret)
71+
if isinstance(ret, SysCall):
72+
ret.handle()
73+
74+
def close(self):
75+
pass
76+
77+
78+
class SysCall:
79+
80+
def __init__(self, call, *args):
81+
self.call = call
82+
self.args = args
83+
84+
class Sleep(SysCall):
85+
86+
def handle(self):
87+
time.sleep(self.args[0])
88+
89+
90+
def sleep(secs):
91+
yield Sleep("sleep", secs)
92+
93+
def sleep2(secs):
94+
t = time.time()
95+
# print("Started sleep:", t, "targetting:", t + secs)
96+
while time.time() < t + secs:
97+
time.sleep(0.01)
98+
yield None
99+
# print("Finished sleeping", secs)
100+
# time.sleep(secs)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy