python協程

來源:互聯網
上載者:User

標籤: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協程

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.