相关疑难解决方法(0)

将asyncio与多工作程序ProcessPoolExecutor结合使用

是否可以采用阻塞功能,work并使其在ProcessPoolExecutor具有多个工作线程的情况下同时运行?

import asyncio
from time import sleep, time
from concurrent.futures import ProcessPoolExecutor

num_jobs = 4
queue = asyncio.Queue()
executor = ProcessPoolExecutor(max_workers=num_jobs)
loop = asyncio.get_event_loop()

def work():
    sleep(1)

async def producer():
    for i in range(num_jobs):
        results = await loop.run_in_executor(executor, work)
        await queue.put(results)

async def consumer():
    completed = 0
    while completed < num_jobs:
        job = await queue.get()
        completed += 1

s = time()
loop.run_until_complete(asyncio.gather(producer(), consumer()))
print("duration", time() - s)
Run Code Online (Sandbox Code Playgroud)

在具有4个以上内核的计算机上运行上述操作需要大约4秒钟.你怎么写producer这样的,上面的例子只需要约1秒钟?

python python-asyncio

4
推荐指数
2
解决办法
2094
查看次数

如何在python中实现asyncio工作队列?

我需要为 aiohttp 创建工作队列。

现在我使用 asyncio.gather,但它的工作方式错误:

在此输入图像描述

这就是我想做的:

在此输入图像描述

第一个可以用以下代码实现:

async def some_stuff(_):
    pass

tasks = []
for i in data:
    tasks.append(do_stuff(i))

asyncio.run(asyncio.gather(*tasks))

Run Code Online (Sandbox Code Playgroud)

我需要的例子

python python-asyncio

1
推荐指数
1
解决办法
3022
查看次数

标签 统计

python ×2

python-asyncio ×2