python协程

Posted zhan-nlp

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python协程相关的知识,希望对你有一定的参考价值。

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协程的主要内容,如果未能解决你的问题,请参考以下文章

Python中的协程与asyncio原理

Python中的协程与asyncio原理

Python中的协程与asyncio原理

python3之协程

python协程

python协程