Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class consume:
- STOP = object()
- def __init__(self, next_val, consumed, used_cnt):
- self.start = True
- self.next_val = next_val
- self.consumed = consumed
- self.used_cnt = used_cnt
- self.loop = asyncio.get_event_loop()
- def __aiter__(self):
- return self
- async def __anext__(self):
- if not self.start:
- self.used_cnt[0] -= 1
- if not self.used_cnt[0]:
- self.consumed[0].set_result(None)
- self.consumed[0] = self.loop.create_future()
- self.next_val[0] = self.loop.create_future()
- self.used_cnt[0] = 2
- else:
- await self.consumed[0]
- else:
- self.start = False
- val = await self.next_val[0]
- if val is consume.STOP:
- raise StopAsyncIteration
- return val
- async def max_and_sum_asyncio(it):
- loop = asyncio.get_event_loop()
- next_val = [loop.create_future()]
- consumed = [loop.create_future()]
- used_cnt = [2]
- async def produce():
- for elem in it:
- next_val[0].set_result(elem)
- await consumed[0]
- next_val[0].set_result(consume.STOP)
- produce_task = loop.create_task(produce())
- s, m = await asyncio.gather(asum(consume(next_val, consumed, used_cnt)), amax(consume(next_val, consumed, used_cnt)))
- await produce_task
- return s, m
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement