我有一个long_task
函数,它运行大量的cpu绑定计算,我想通过使用新的asyncio框架使其异步。生成的long_task_async
函数使用ProcessPoolExecutor
将工作卸载到不同的进程,而不受GIL的约束。
问题在于,由于某种原因,当从throws aTypeError
产生时,从ProcessPoolExecutor.submit
返回的concurrent.futures.Future
实例。这是故意的吗?这些未来与asyncio.Future
类不兼容吗?什么是解决办法?
我还注意到生成器是不可选择的,因此向ProcessPoolExecutor
提交coutroutine将失败。有什么干净的解决办法吗?
import asyncio
from concurrent.futures import ProcessPoolExecutor
@asyncio.coroutine
def long_task():
yield from asyncio.sleep(4)
return "completed"
@asyncio.coroutine
def long_task_async():
with ProcessPoolExecutor(1) as ex:
return (yield from ex.submit(long_task)) #TypeError: 'Future' object is not iterable
# long_task is a generator, can't be pickled
loop = asyncio.get_event_loop()
@asyncio.coroutine
def main():
n = yield from long_task_async()
print( n )
loop.run_until_complete(main())
我们可以通过调用
asyncio.wrap_future(Future)
将concurrent.futures.Future
包装成asyncio.future
。我用下面的代码试过了。工作正常您希望使用^{} ,它使用
concurrent.futures
执行器,但将返回值映射到asyncio
未来。最初的}可能有一天会增长一个
asyncio
PEP suggests that{__iter__
方法,因此它也可以与yield from
一起使用,但目前库的设计只需要yield from
支持,而不需要更多支持。(否则某些代码实际上在3.3中不起作用。)相关问题 更多 >
编程相关推荐