线程的缺点:在Python解释器中有一个GIL锁 — Global Interpreter Lock,在Python中的线程执行前都会获得这个GIL锁,每次执行100条字节码后,解释器就自动释放这个GIL锁,让别的线程有机会执行。Python会把所有的线程都加上这把锁,然后多线程之间只能交替执行,并未实现真正的并发执行。
使用协程可以避免,相当于异步编程
# 引入协程包
import asyncio
import time
def demoAsync():
# 使用async修饰普通函数,可将普通函数变成异步函数
async def task1():
print("Execute the first task...")
# 耗时操作使用await修饰,这样会随机进入下一个协程函数执行
await asyncio.sleep(3)
print("the first task is done....")
async def task2():
print("Execute the second task...")
await asyncio.sleep(3)
print("the second task is done...")
async def task3():
print("Execute the third task...")
await asyncio.sleep(3)
print("the third task is done...")
# 创建任务事件循环
loop = asyncio.get_event_loop()
# 将异步任务加入到一个列表中,形成任务列表
tasks = [task1(), task2(), task3()]
# 开始任务事件循环,直到最后一个任务执行结束
loop.run_until_complete(asyncio.wait(tasks))
# 最后一个任务执行结束后,关闭循环
loop.close()
def demoNormal():
def task1():
print("Execute the first task...")
# 耗时操作使用await修饰,这样会随机进入下一个协程函数执行
time.sleep(3)
print("the first task is done....")
def task2():
print("Execute the second task...")
time.sleep(3)
print("the second task is done...")
def task3():
print("Execute the third task...")
time.sleep(3)
print("the third task is done...")
task1()
task2()
task3()
if __name__ == '__main__':
startAsync = time.time()
demoAsync()
endAsync = time.time()
# 用了异步执行,大概使用3s左右的时间 Async Time:3.0043070316314697
print(str("Async Time:" + str(endAsync - startAsync)))
startNormal = time.time()
demoNormal()
endNormal = time.time()
# 不用异步,则打印出来的时间应该时9s左右 Normal time:9.009456157684326
print(str("Normal time:" + str(endNormal - startNormal)))