协程
协程是在单个线程下边执行的东西,遇到IO请求阻塞,切换到另外的协程任务运行。
(按摩技师相当于一个协程,当按摩过程中泡脚的时候(相当于遇到IO请求),技师会先给捏背,当捏背过程完毕或者又有其他导致不能继续(相当于IO请求),
这时候泡脚完毕会切换到可以执行的别的任务))
单个协程任务调用方式及实例:
import asyncio import time async def func(): print("你好,我叫赛利亚") if __name__ == '__main__': g = func() #此时的函数是一个异步协程函数,此时函数执行得到的结果是一个协程对象 print(g) asyncio.run(g) #协程函数执行需要得到asyncio模块的支持
打印g的结果:
<coroutine object func at 0x000001AA9720B200>
多协程任务调用之后报错:AttributeError: module 'asyncio' has no attribute 'run'
asyncio.run(asyncio.wait(task))
替换成
asyncio.get_event_loop().run_until_complete(asyncio.gather(*task))
替换之后运行结果:
多个协程任务完整代码:
import asyncio import time async def func1(): print("你好,我叫赛利亚") await asyncio.sleep(3) print("你好,我叫赛利亚") async def func2(): print("你好,我叫潘金莲") await asyncio.sleep(2) print("你好,我叫潘金莲") async def func3(): print("你好,我叫曹雪芹") await asyncio.sleep(4) print("你好,我叫曹雪芹") if __name__ == '__main__': a = func1() b = func2() c = func2() task = [a,b,c] t1 = time.time() # asyncio.run(asyncio.wait(task)) asyncio.get_event_loop().run_until_complete(asyncio.gather(*task)) t2 = time.time() print(t2-t1)
优化版:
import asyncio import time async def func1(): print("你好,我叫赛利亚") await asyncio.sleep(3) print("你好,我叫赛利亚") async def func2(): print("你好,我叫潘金莲") await asyncio.sleep(2) print("你好,我叫潘金莲") async def func3(): print("你好,我叫曹雪芹") await asyncio.sleep(4) print("你好,我叫曹雪芹") async def main(): task=[ func1(), func2(), func3() ] await asyncio.wait(task) if __name__ == '__main__': t1 = time.time() # asyncio.run(main()) asyncio.get_event_loop().run_until_complete(main()) t2 = time.time() print(t2-t1)