码迷,mamicode.com
首页 > 编程语言 > 详细

python协程

时间:2018-06-21 17:25:26      阅读:151      评论:0      收藏:0      [点我收藏+]

标签: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 + 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()

 

python协程

标签:imp   nis   and   span   实现   div   event   while   TE   

原文地址:https://www.cnblogs.com/zhan-nlp/p/9209398.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!