标签:run 任务 join style 多进程 main int range sleep
# 1:单核上的协程
import asyncio
import time
async def test(time):
await asyncio.sleep(time)
async def main():
start_time = time.time()
# 创建任务
tasks = [asyncio.create_task(test(1)) for _ in range(10000)]
# 将任务丢到执行队列里面去
[await t for t in tasks]
print(time.time() - start_time)
if __name__ == "__main__":
asyncio.run(main())
# 多核上的协程:(多进程 + 协程)
from multiprocessing import Pool
import asyncio
import time
async def test1(time):
await asyncio.sleep(time)
async def main1(num):
start_time = time.time()
tasks = [asyncio.create_task(test1(1)) for _ in range(num)]
[await t for t in tasks]
print(time.time() - start_time)
def run(num):
asyncio.run(main1(num))
if __name__ == "__main__":
p = Pool()
for i in range(4):
p.apply_async(run, args=(2500,))
p.close()
p.join()
标签:run 任务 join style 多进程 main int range sleep
原文地址:https://www.cnblogs.com/zhouzetian/p/12055578.html