example23.py 1010 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """
  2. 协程(coroutine)- 可以在需要时进行切换的相互协作的子程序
  3. """
  4. import asyncio
  5. from example15 import is_prime
  6. def num_generator(m, n):
  7. """指定范围的数字生成器"""
  8. yield from range(m, n + 1)
  9. async def prime_filter(m, n):
  10. """素数过滤器"""
  11. primes = []
  12. for i in num_generator(m, n):
  13. if is_prime(i):
  14. print('Prime =>', i)
  15. primes.append(i)
  16. await asyncio.sleep(0.001)
  17. return tuple(primes)
  18. async def square_mapper(m, n):
  19. """平方映射器"""
  20. squares = []
  21. for i in num_generator(m, n):
  22. print('Square =>', i * i)
  23. squares.append(i * i)
  24. await asyncio.sleep(0.001)
  25. return squares
  26. def main():
  27. """主函数"""
  28. loop = asyncio.get_event_loop()
  29. future = asyncio.gather(prime_filter(2, 100), square_mapper(1, 100))
  30. future.add_done_callback(lambda x: print(x.result()))
  31. loop.run_until_complete(future)
  32. loop.close()
  33. if __name__ == '__main__':
  34. main()