我有一个long_task
运行繁重的 cpu-bound 计算的函数,我想通过使用新的 asyncio 框架使其异步。生成的long_task_async
函数使用 aProcessPoolExecutor
将工作卸载到不受 GIL 约束的不同进程。
问题在于,由于某种原因,当 yield from 时concurrent.futures.Future
返回的实例ProcessPoolExecutor.submit
会抛出一个TypeError
. 这是设计使然吗?asyncio.Future
那些期货与阶级不兼容吗?什么是解决方法?
我还注意到生成器不可腌制,因此向 couroutine 提交ProcessPoolExecutor
会失败。有什么干净的解决方案吗?
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())