协程,又称微线程。协程的作用是在执行函数A时可以随时中断去执行函数B,然后中断函数B继续执行函数A(可以自由切换)。但这一过程并不是函数调用,这一整个过程看似像多线程,但是协程仅在一个线程执行。
简单来讲,协程就是程序在碰到阻塞状态时能够选择性地切换到其他任务上。关于程序阻塞状态,一般程序进行IO操作时,线程会处入阻塞状态。在爬虫中,requests.get()也会使程序处入阻塞状态。
python中实现异步协程需要导入asyncio库。
下面我们将通过实例了解协程以及python中协程的基本实现。
import asyncio
import time
async def test_1():
print('1,点赞')
time.sleep(2)
print('1,点赞')
async def test_2():
print('2,收藏')
time.sleep(3)
print('2,收藏')
async def test_3():
print('3,分享')
time.sleep(4)
print('3,分享')
if __name__ == '__main__':
t1 = test_1()
t2 = test_2()
t3 = test_3()
tasks = [t1,t2,t3]
time1 = time.time()
asyncio.run(asyncio