目標
用一個等待過程理解,能夠實現一致的方便,70行代碼
例子說明
某方需要2,執行req2需要執行這個時間,最終執行時間是3秒,大約1秒,同時執行;如果最終時間是秒,如果執行的話,具體請參看,友情提示是,yield from 方法后面如果是它的工具,可以進入____
import time
from collections import deque
_delay = deque()
class FutureX:
def __init__(self, coro=None, delay_second=None):
self.coro = coro
if delay_second:
self.start = delay_second + time.time()
def step(self):
coro = self.coro
try:
result = coro.send(None)
except StopIteration as e:
print(e.value)
pass
else:
if isinstance(result, FutureX):
_delay.append((self._wakeup, result))
else:
pass
def _wakeup(self):
self.step()
def __iter__(self):
yield self
return None
def coroutine(func):
co = func.__code__
func.__code__ = co.replace(co_flags=co.co_flags | 0x100)
return func
@coroutine
def sleep0(seconds):
future = FutureX(delay_second=seconds)
b = yield from future
return seconds
async def req1(delay_seconds):
resp_time = await sleep0(delay_seconds)
return resp_time
async def req2(delay_seconds):
resp_time = await sleep0(delay_seconds)
return resp_time
t1 = time.time()
f1, f2 = FutureX(req1(2)), FutureX(req2(1))
f1.step()
f2.step()
while _delay:
callback, args = _delay.popleft()
start = args.start
if not start:
continue
while True:
end = time.time()
if start <= end:
try:
callback()
except StopIteration as e:
pass
break
print(f'花費的時間:{round(time.time() - t1,1)}')
'''
結果:
2
1
花費的時間:2.0
'''
審核編輯:劉清
-
python
+關注
關注
56文章
4802瀏覽量
84890
發布評論請先 登錄
相關推薦
評論