python3.5为asyncio提供了async和await语法,利用这两个可简化协程的实现。
1 import asyncio 2 import random 3 4 5 async def smart_fib(n): 6 index = 0 7 a = 0 8 b = 1 9 while index < n: 10 sleep_secs = random.uniform(0, 0.2) 11 await asyncio.sleep(sleep_secs) 12 print(‘Smart one think {} secs to get {}‘.format(sleep_secs, b)) 13 a, b = b, a + b 14 index += 1 15 16 17 async def stupid_fib(n): 18 index = 0 19 a = 0 20 b = 1 21 while index < n: 22 sleep_secs = random.uniform(0, 0.4) 23 await asyncio.sleep(sleep_secs) 24 print(‘Stupid one think {} secs to get {}‘.format(sleep_secs, b)) 25 a, b = b, a + b 26 index += 1 27 28 29 30 if __name__ == ‘__main__‘: 31 loop = asyncio.get_event_loop() 32 tasks = [ 33 asyncio.ensure_future(smart_fib(10)), 34 asyncio.ensure_future(stupid_fib(10)), 35 ] 36 loop.run_until_complete(asyncio.wait(tasks)) 37 print(‘All fib finished.‘) 38 loop.close()
原文:https://www.cnblogs.com/zhan-nlp/p/9209398.html