我是应该在代码中替换while True (没有异步),还是应该使用异步事件循环来实现相同的结果。
目前,我工作的是某种类型的“工作者”,它连接到zeromq,接收一些数据,然后对外部工具(服务器)执行一些请求(http)。所有东西都是用普通的阻塞IO编写的。使用异步事件循环来消除while True: ...是否有意义?
将来可能会完全用异步重写,但现在我害怕从异步开始。
我是新来的异步的,并不是这个库的所有部分对我来说都很清楚:)
Thx :)
发布于 2015-09-24 15:04:40
如果您想开始使用不支持异步代码的库编写异步代码,可以使用遗嘱执行人。
这允许您提交一个可调用的ThreadPoolExecutor或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)https://stackoverflow.com/questions/32761095
复制相似问题