fork download
  1. import asyncio
  2. import time
  3. from functools import partial
  4.  
  5. NAMES = ['Martha', 'John', 'Vasyan', 'Goga']
  6.  
  7.  
  8. async def cb(context):
  9. nickname = context.get('nickname')
  10. print(f'CB FOR {nickname} CALLED')
  11. await asyncio.sleep(1)
  12. print(f'CB FOR {nickname} END')
  13.  
  14.  
  15. async def f(name):
  16. print(f'{name} CALLED')
  17. await asyncio.sleep(2)
  18. print(f'{name} END')
  19.  
  20.  
  21. async def test():
  22. futures = []
  23. for name in NAMES:
  24.  
  25. async def coro(name):
  26. await f(name)
  27. await cb({'nickname': name})
  28.  
  29. futures.append(coro(name))
  30.  
  31. await asyncio.gather(*futures)
  32. await asyncio.sleep(2)
  33.  
  34. start = time.time()
  35. asyncio.run(test())
  36. end = time.time()
  37. print(f'Took {end-start} secs')
  38.  
Success #stdin #stdout 0.1s 16148KB
stdin
Standard input is empty
stdout
Martha CALLED
John CALLED
Vasyan CALLED
Goga CALLED
Martha END
CB FOR Martha CALLED
John END
CB FOR John CALLED
Vasyan END
CB FOR Vasyan CALLED
Goga END
CB FOR Goga CALLED
CB FOR Martha END
CB FOR John END
CB FOR Vasyan END
CB FOR Goga END
Took 5.0207273960113525 secs