1 Star 0 Fork 0

yunni/python_eventloop

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
03eventLoop.py 2.35 KB
一键复制 编辑 原始数据 按行查看 历史
yunni 提交于 2022-06-18 20:24 . done
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()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/linlinstyle/python_eventloop.git
[email protected]:linlinstyle/python_eventloop.git
linlinstyle
python_eventloop
python_eventloop
master

搜索帮助