我正在创建一个Python应用程序,我在其中接收一些数据,并且需要处理这些数据。由于我一直在接收数据,因此无法同步执行此操作,因此需要同时处理数据。
问题是我使用的库不支持asyncio
,所以我不知道是否可以同时运行它。这是我的代码:
async def event_dispatcher(num):
data = blocking_operation(num)
print(data)
async def main():
tasks = [loop.create_task(event_dispatcher(1)), loop.create_task(event_dispatcher(2)), loop.create_task(event_dispatcher(3)),
loop.create_task(event_dispatcher(4)), loop.create_task(event_dispatcher(5)), loop.create_task(event_dispatcher(6))]
await asyncio.gather(*tasks)
blocking_operation
我不能同时运行的功能在哪里?因此,基本上我希望函数tasks
同时运行,但是由于blocking_operation
,它们将同时运行一个。有什么办法解决这个问题?还是我被迫使用另一个库或多处理程序?
您可以使用run_in_executor
,它将在后台的线程池中提交阻塞代码:
async def event_dispatcher(num):
loop = asyncio.get_event_loop()
data = await loop.run_in_executor(None, blocking_operation, num)
print(data)
从Python 3.9开始,您还可以使用asyncio.to_thread
:
async def event_dispatcher(num):
data = await asyncio.to_thread(blocking_operation, num)
print(data)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句