异步与多线程多进程:
async与await关键字
用法:
# 定义异步函数
async def test(a):
return a
# 执行异步
async def t2():
res = await test(1)
用法:
async def main():
result = await asyncio.gather(a(),b())
print(result)
if __name__ == '__main__':
asyncio.run(main())
例1:非异步
import time
import os
def test1():
for i in range(3):
print(f'test1,i={i},进程号:{os.getpid()}')
time.sleep(1)
def test2():
for j in range(3):
print(f'test2,j={j},进程号:{os.getpid()}')
time.sleep(1)
if __name__ == '__main__':
# 开始时间
start_time = time.time()
test1()
test2()
print(f'时间间隔:{time.time()-start_time},进程号:{os.getpid()}')
结果:
例2:异步
import time
import os
import asyncio
import threading
# 定义异步函数
async def test1():
for i in range(3):
print(f'test1,i={i},进程号:{os.getpid()},线程名称是:{threading.current_thread().name}')
# 注意这里的等待时间也要修改成异步
# time.sleep是cpu阻塞,asyncio.sleep是当前业务阻塞
await asyncio.sleep(1)
return "test1"
async def test2():
for j in range(3):
print(f'test2,j={j},进程号:{os.getpid()},线程名称是:{threading.current_thread().name}')
# 注意这里的等待时间也要修改
await asyncio.sleep(1)
return "test2"
# 定义主异步函数
async def main():
# 批量执行异步函数
result = await asyncio.gather(test1(), test2())
# 打印函数的返回值
print(f'函数返回值:{result},线程名称是:{threading.current_thread().name}')
return '我是主函数'
if __name__ == '__main__':
# 开始时间
start_time = time.time()
# 执行主异步函数
ar = asyncio.run(main())
print(f'{ar},线程名称是:{threading.current_thread().name}')
print(f'时间间隔:{time.time()-start_time},进程号:{os.getpid()},线程名称是:{threading.current_thread().name}')
结果:
环境准备
安装 pip install gevent
例:
import time
import os
import gevent
import threading
def test1(count):
for i in range(count):
print(f'test1,i={i},进程号:{os.getpid()},线程名称是:{threading.current_thread().name}')
# 注意这里的时间也要修改成异步
gevent.sleep(1)
return "test1"
def test2():
for j in range(3):
print(f'test2,j={j},进程号:{os.getpid()},线程名称是:{threading.current_thread().name}')
# 注意这里的时间也要修改
gevent.sleep(1)
return "test2"
if __name__ == '__main__':
# 开始时间
start_time = time.time()
# 创建协程对象
g1 = gevent.spawn(test1, 3)
g2 = gevent.spawn(test2)
# 批量处理协程对象
g_list = [g1, g2]
result = gevent.joinall(g_list)
# 打印异步函数的返回值
# 方式1:
print(f'test1函数返回值:{g1.get()}')
# 方式2:
print(result[0].value, result[1].value)
print(f'时间间隔:{time.time()-start_time},进程号:{os.getpid()},线程名称是:{threading.current_thread().name}')