async for
함께 (주로) 정기적 인 간격으로 새 값을 반환해야하는 비동기 iterator를 구현하고 있습니다.정기적 인 간격으로 비동기 iterator를 틱
import asyncio
class Clock(object):
def __init__(self, interval=1):
self.counter = 0
self.interval = interval
self.tick = asyncio.Event()
asyncio.ensure_future(self.tick_tock())
async def tick_tock(self):
while True:
self.tick.clear()
await asyncio.sleep(self.interval)
self.counter = self.__next__()
self.tick.set()
def __next__(self):
self.counter += 1
return self.counter
def __aiter__(self):
return self
async def __anext__(self):
await self.tick.wait()
return self.counter
이 asyncio.Event
를 사용하는 것보다 더 나은 또는 청소기 방법이 있나요 :
우리는 n 초 ~ 모든 카운터를 증가하는 간단한 시계와 같은 반복자를 설명 할 수 있습니까? 이 반복자에서 두 개 이상의 코 루틴이 async for
입니다.
문제는 이터레이터를 여러 동시 루틴이 동시에 사용할 수 있다는 것입니다. 그래서'asyncio.Event'를 사용했습니다. – DurandA