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

最佳答案

您可以在主事件循环中执行计算工作,但是在发生这种情况时,整个事件循环将被阻止-无法满足其他请求,并且您在事件循环中运行的任何其他操作都将被阻止。如果这是 Not Acceptable ,则可能要使用 BaseEventLoop.run_in_executor 在单独的进程中运行计算工作。这是一个非常简单的示例演示:

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操作一样等待结果,因此它不会阻塞其他协程的运行。

关于python - 我应该在一个程序中使用两个asyncio事件循环吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27290656/

10-12 13:33