朋友们,之前你可能看过很多的文章都是关于python异步的,他们很理论,但是你还是搞不清异步究竟干了什么,今天给大家讲一讲。

首先,异步干了什么?        Python中异步编程通过协程来实现,主要使用asyncio库。异步编程的优势在于可以提高程序的吞吐量和响应速度,因为异步代码能够充分利用 CPU 时间,同时不会阻塞其他代码的执行。

再者,如何实现? import asyncio import time st = time.time() async def my_coroutine(): print("Coroutine started") await asyncio.sleep(2) # 模拟耗时操作 print("Coroutine finished")

async def another_coroutine(): print("Another coroutine started") await asyncio.sleep(1) # 模拟另一个耗时操作 print("Another coroutine finished")

async def main(): task1 = asyncio.create_task(my_coroutine()) task2 = asyncio.create_task(another_coroutine()) await asyncio.gather(task1, task2)

获取当前事件循环

loop = asyncio.get_event_loop()

运行协程

loop.run_until_complete(main()) ed = time.time() print(ed-st)

你重复多次运行上面的代码,你看看结果会怎么返回?

如上图,你运行的时候,输出顺序是下面:

如上图,你可以看到,当我把两个task放到一个协程管理器里面的时候, 1执行完了,在sleep2的时候,他并没有真的阻塞了2s,而是直接跳到了another_coroutine方法里面执行了,因为如果他真的sleep2,后面another_coroutine的sleep1加起来一共是3s,但是最终输出的时候,一共是2.004s,说明sleep的时候,实际上是去执行别的了,而不是闲着,这就相当于节省了将近1s的时间,这就是异步真正节省时间的地方,所以,你懂了吗?