Advertisement
Guest User

Untitled

a guest
Jul 28th, 2018
826
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. class consume:
  2.     STOP = object()
  3.  
  4.     def __init__(self, next_val, consumed, used_cnt):
  5.         self.start = True
  6.         self.next_val = next_val
  7.         self.consumed = consumed
  8.         self.used_cnt = used_cnt
  9.         self.loop = asyncio.get_event_loop()
  10.  
  11.     def __aiter__(self):
  12.         return self
  13.  
  14.     async def __anext__(self):
  15.         if not self.start:
  16.             self.used_cnt[0] -= 1
  17.             if not self.used_cnt[0]:
  18.                 self.consumed[0].set_result(None)
  19.                 self.consumed[0] = self.loop.create_future()
  20.                 self.next_val[0] = self.loop.create_future()
  21.                 self.used_cnt[0] = 2
  22.             else:
  23.                 await self.consumed[0]
  24.         else:
  25.             self.start = False
  26.  
  27.         val = await self.next_val[0]
  28.         if val is consume.STOP:
  29.             raise StopAsyncIteration
  30.         return val
  31.  
  32.  
  33. async def max_and_sum_asyncio(it):
  34.     loop = asyncio.get_event_loop()
  35.  
  36.     next_val = [loop.create_future()]
  37.     consumed = [loop.create_future()]
  38.     used_cnt = [2]
  39.  
  40.     async def produce():
  41.         for elem in it:
  42.             next_val[0].set_result(elem)
  43.             await consumed[0]
  44.         next_val[0].set_result(consume.STOP)
  45.  
  46.     produce_task = loop.create_task(produce())
  47.     s, m = await asyncio.gather(asum(consume(next_val, consumed, used_cnt)), amax(consume(next_val, consumed, used_cnt)))
  48.     await produce_task
  49.  
  50.     return s, m
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement