- commit
- 558404f360c439a891c61eb01cfdd27a9631ea44
- parent
- ca80ef33ab9cc8fd7033858bd60c5f767e124326
- Author
- Tobias Bengfort <tobias.bengfort@posteo.de>
- Date
- 2023-02-04 17:42
add 08_asyncio_futures.py
Diffstat
| A | 08_asyncio_futures.py | 64 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 files changed, 64 insertions, 0 deletions
diff --git a/08_asyncio_futures.py b/08_asyncio_futures.py
@@ -0,0 +1,64 @@
-1 1 import asyncio
-1 2
-1 3
-1 4 class Future:
-1 5 def __init__(self):
-1 6 self.callbacks = []
-1 7 self.result = None
-1 8 self.exception = None
-1 9 self.done = False
-1 10
-1 11 def _set_done(self):
-1 12 self.done = True
-1 13 for callback in self.callbacks:
-1 14 callback(self)
-1 15
-1 16 def set_result(self, result):
-1 17 self.result = result
-1 18 self._set_done()
-1 19
-1 20 def set_exception(self, exception):
-1 21 self.exception = exception
-1 22 self._set_done()
-1 23
-1 24 def add_done_callback(self, callback):
-1 25 self.callbacks.append(callback)
-1 26
-1 27 def __await__(self):
-1 28 yield self
-1 29
-1 30
-1 31 class Task:
-1 32 def __init__(self, coro):
-1 33 self.gen = coro.__await__()
-1 34
-1 35 def wakeup(self, future=None):
-1 36 try:
-1 37 if future and future.exception:
-1 38 new_future = self.gen.throw(future.exception)
-1 39 else:
-1 40 new_future = next(self.gen)
-1 41 new_future.add_done_callback(self.wakeup)
-1 42 except StopIteration:
-1 43 pass
-1 44
-1 45
-1 46 async def sleep(t):
-1 47 future = Future()
-1 48 loop.call_later(t, future.set_result, None)
-1 49 await future
-1 50
-1 51
-1 52 async def amain():
-1 53 print('start')
-1 54 try:
-1 55 await sleep(5)
-1 56 loop.stop()
-1 57 finally:
-1 58 print('finish')
-1 59
-1 60
-1 61 loop = asyncio.new_event_loop()
-1 62 task = Task(amain())
-1 63 task.wakeup()
-1 64 loop.run_forever()