代码拉取完成,页面将自动刷新
import collections
import heapq
import itertools
import random
import time
from time import sleep
class EventLoop(object):
_instance = None
@staticmethod
def get_event_loop():
if EventLoop._instance is None:
EventLoop._instance = EventLoop()
return EventLoop._instance
def __init__(self):
self._ready = collections.deque()
self._delay = []
self._isStop = False
def call_soon(self, cb, *args):
self._ready.append((cb, args))
def call_latter(self, delay, cb, *args):
t = time.time() + delay
heapq.heappush(self._delay, (t, cb, args))
def run_forever(self):
while True:
self.run_once()
if self._isStop:
break
def stop(self):
self._isStop = True
def run_once(self):
now = time.time()
if self._delay:
if self._delay[0][0] < now:
_, cb, args = heapq.heappop(self._delay)
self._ready.append((cb, args))
num = len(self._ready)
for i in range(num):
cb, args = self._ready.popleft()
cb(*args)
class Awaitable(object):
def __init__(self, obj):
self.value = obj
def __await__(self):
yield self
task_id_counter = itertools.count(1)
class Task(object):
def __init__(self, coro):
self.coro = coro
self._done = False
self._result = None
self._id = f'Task-{next(task_id_counter)}'
def run(self):
print(f'----- {self._id} -----')
if not self._done:
try:
x = self.coro.send(None)
except StopIteration as e:
self._result = e.value
self._done = True
else:
assert isinstance(x, Awaitable)
loop.call_latter(x.value, self.run)
else:
print('task is done')
async def small_step():
print('休息一下,马上回来')
t1 = time.time()
sleep_time = random.random()
await Awaitable(sleep_time)
assert time.time() - t1 > sleep_time, "睡眠时间不足"
print('努力工作中')
return 123
if __name__ == '__main__':
loop = EventLoop.get_event_loop()
for i in range(10):
t = Task(small_step())
loop.call_soon(t.run)
loop.call_latter(2.1, loop.stop)
loop.run_forever()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。