Skip to content

Commit 9c06d91

Browse files
author
Paul Sokolovsky
committed
WIP uasyncio.core: Trying to implement wait_for function.
Contains history of previous attempts. Only pend_throw() works as expected.
1 parent 03bb3ad commit 9c06d91

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

uasyncio.core/uasyncio/core.py

+61
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,15 @@ def set_debug(val):
1515
log = logging.getLogger("uasyncio.core")
1616

1717

18+
class TimeoutError(Exception):
19+
pass
20+
21+
1822
class EventLoop:
1923

2024
def __init__(self, len=42):
2125
self.q = utimeq.utimeq(len)
26+
self.timed_out = {}
2227

2328
def time(self):
2429
return time.ticks_ms()
@@ -80,12 +85,18 @@ def run_forever(self):
8085
if callable(cb):
8186
cb(*args)
8287
else:
88+
if cb in self.timed_out:
89+
print("%r timed out" % cb)
90+
1/0
8391
delay = 0
8492
try:
8593
if __debug__ and DEBUG:
8694
log.debug("Coroutine %s send args: %s", cb, args)
8795
if args == ():
8896
ret = next(cb)
97+
elif isinstance(args[0], Exception):
98+
print("Throwing %r into %r" % (args, cb))
99+
cb.throw(*args)
89100
else:
90101
ret = cb.send(*args)
91102
if __debug__ and DEBUG:
@@ -211,6 +222,56 @@ def __next__(self):
211222
_stop_iter = StopIteration()
212223
sleep_ms = SleepMs()
213224

225+
def _wait_for(coro, timeout):
226+
def timeout_func():
227+
print("timeout")
228+
# raise TimeoutError
229+
coro.throw(TimeoutError)
230+
231+
_event_loop.call_later(timeout, timeout_func)
232+
#_event_loop.call_soon(coro)
233+
#_event_loop.run_forever()
234+
res = yield from coro
235+
return res
236+
237+
if 0:
238+
yield
239+
240+
241+
class TimeoutObj:
242+
def __init__(self, coro):
243+
self.coro = coro
244+
self.active = True
245+
def cancel(self):
246+
self.core = None
247+
self.active = False
248+
249+
def wait_for(coro, timeout):
250+
251+
def waiter(coro, to):
252+
res = yield from coro
253+
to.cancel()
254+
return res
255+
256+
def timeout_func(to):
257+
if to.active:
258+
print("timeout_func: cancelling", coro)
259+
# raise TimeoutError
260+
# coro.throw(TimeoutError)
261+
# _event_loop.call_soon(coro, TimeoutError())
262+
# _event_loop.call_soon(w, TimeoutError())
263+
# _event_loop.timed_out[coro] = True
264+
to.coro.pend_throw(TimeoutError())
265+
# w.pend_throw(TimeoutError())
266+
else:
267+
print("timeout_func: timeout was cancelled")
268+
269+
timeout_obj = TimeoutObj(coro)
270+
_event_loop.call_later(timeout, timeout_func, timeout_obj)
271+
w = waiter(coro, timeout_obj)
272+
res = yield from w
273+
return res
274+
214275

215276
def coroutine(f):
216277
return f

0 commit comments

Comments
 (0)