python asyncio run_forever 或者 while True
python asyncio run_forever or while True
我应该在我的代码中替换 while True
(没有 asyncio)还是应该使用 asyncio 事件循环来完成相同的结果。
目前我正在研究某种连接到 zeromq 的 "worker",接收一些数据然后对外部工具(服务器)执行一些请求 (http)。一切都写在 normal 阻塞 IO 中。使用 asyncio 事件循环摆脱 while True: ...
有意义吗?
以后可能会完全用asyncio重写,但现在不敢从asyncio入手了
我是 asyncio 的新手,并不是这个库的所有部分对我来说都很清楚:)
谢谢:)
如果您想使用不支持它的库开始编写 asyncio 代码,可以使用 BaseEventLoop.run_in_executor。
这允许您向 ThreadPoolExecutor or a ProcessPoolExecutor 提交可调用对象并异步获取结果。默认执行器是一个包含 5 个线程的线程池。
示例:
# Python 3.4
@asyncio.coroutine
def some_coroutine(*some_args, loop=None):
while True:
[...]
result = yield from loop.run_in_executor(
None, # Use the default executor
some_blocking_io_call,
*some_args)
[...]
# Python 3.5
async def some_coroutine(*some_args, loop=None):
while True:
[...]
result = await loop.run_in_executor(
None, # Use the default executor
some_blocking_io_call,
*some_args)
[...]
loop = asyncio.get_event_loop()
coro = some_coroutine(*some_arguments, loop=loop)
loop.run_until_complete(coro)
我应该在我的代码中替换 while True
(没有 asyncio)还是应该使用 asyncio 事件循环来完成相同的结果。
目前我正在研究某种连接到 zeromq 的 "worker",接收一些数据然后对外部工具(服务器)执行一些请求 (http)。一切都写在 normal 阻塞 IO 中。使用 asyncio 事件循环摆脱 while True: ...
有意义吗?
以后可能会完全用asyncio重写,但现在不敢从asyncio入手了
我是 asyncio 的新手,并不是这个库的所有部分对我来说都很清楚:)
谢谢:)
如果您想使用不支持它的库开始编写 asyncio 代码,可以使用 BaseEventLoop.run_in_executor。
这允许您向 ThreadPoolExecutor or a ProcessPoolExecutor 提交可调用对象并异步获取结果。默认执行器是一个包含 5 个线程的线程池。
示例:
# Python 3.4
@asyncio.coroutine
def some_coroutine(*some_args, loop=None):
while True:
[...]
result = yield from loop.run_in_executor(
None, # Use the default executor
some_blocking_io_call,
*some_args)
[...]
# Python 3.5
async def some_coroutine(*some_args, loop=None):
while True:
[...]
result = await loop.run_in_executor(
None, # Use the default executor
some_blocking_io_call,
*some_args)
[...]
loop = asyncio.get_event_loop()
coro = some_coroutine(*some_arguments, loop=loop)
loop.run_until_complete(coro)