標籤:imp nis and span 實現 div event while TE
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 + b14 index += 115 16 17 async def stupid_fib(n):18 index = 019 a = 020 b = 121 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 + b26 index += 127 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()
python協程