我应该在一个程序中使用两个 asyncio 事件循环吗? [英] Should I use two asyncio event loops in one program?

查看:41
本文介绍了我应该在一个程序中使用两个 asyncio 事件循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Python 3 asyncio 模块来创建服务器应用程序.我使用一个主事件循环来监听网络,当接收到新数据时,它会做一些计算并将结果发送给客户端.做一些计算"需要一个新的事件循环吗?还是可以使用主事件循环?

I want use the Python 3 asyncio module to create a server application. I use a main event loop to listen to the network, and when new data is received it will do some compute and send the result to the client. Does 'do some compute' need a new event loop? or can it use the main event loop?

推荐答案

您可以在主事件循环中完成计算工作,但在发生这种情况时整个事件循环将被阻塞 - 无法处理其他请求,以及任何其他请求否则你在事件循环中运行将被阻止.如果这是不可接受的,您可能希望在单独的进程中运行计算工作,使用 BaseEventLoop.run_in_executor.这是一个非常简单的示例来演示它:

You can do the compute work in the main event loop, but the whole event loop will be blocked while that happens - no other requests can be served, and anything else you have running in the event loop will be blocked. If this isn't acceptable, you probably want to run the compute work in a separate process, using BaseEventLoop.run_in_executor. Here's a very simple example demonstrating it:

import time
import asyncio
from concurrent.futures import ProcessPoolExecutor

def cpu_bound_worker(x, y):
    print("in worker")
    time.sleep(3)
    return x +y

@asyncio.coroutine
def some_coroutine():
    yield from asyncio.sleep(1)
    print("done with coro")

@asyncio.coroutine
def main():
    loop = asyncio.get_event_loop()
    loop.set_default_executor(ProcessPoolExecutor())
    asyncio.async(some_coroutine())
    out = yield from loop.run_in_executor(None, cpu_bound_worker, 3, 4)
    print("got {}".format(out))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

输出:

in worker
done with coro
got 7

cpu_bound_worker 在子进程中执行,事件循环将像等待任何其他非阻塞 I/O 操作一样等待结果,因此它不会阻止其他协程运行.

cpu_bound_worker gets executed in a child process, and the event loop will wait for the result like it would any other non-blocking I/O operation, so it doesn't block other coroutines from running.

这篇关于我应该在一个程序中使用两个 asyncio 事件循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆