example_of_coroutine.py 1.1 KB

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