testaio2.py 771 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import asyncio
  2. import random
  3. @asyncio.coroutine
  4. def smart_fib(n):
  5. index = 0
  6. a = 0
  7. b = 1
  8. while index < n:
  9. sleep_secs = random.uniform(0, 0.2)
  10. yield from asyncio.sleep(sleep_secs)
  11. print('Smart one think {} secs to get {}'.format(sleep_secs, b))
  12. a, b = b, a + b
  13. index += 1
  14. @asyncio.coroutine
  15. def stupid_fib(n):
  16. index = 0
  17. a = 0
  18. b = 1
  19. while index < n:
  20. sleep_secs = random.uniform(0, 0.4)
  21. yield from asyncio.sleep(sleep_secs)
  22. print('Stupid one think {} secs to get {}'.format(sleep_secs, b))
  23. a, b = b, a + b
  24. index += 1
  25. if __name__ == '__main__':
  26. loop = asyncio.get_event_loop()
  27. tasks = [
  28. asyncio.async(smart_fib(10)),
  29. asyncio.async(stupid_fib(10)),
  30. ]
  31. loop.run_until_complete(asyncio.wait(tasks))
  32. print('All fib finished.')
  33. loop.close()