【发布时间】:2014-04-22 02:36:23
【问题描述】:
我有一个 long_task 函数,它运行大量的 cpu 绑定计算,我想通过使用新的 asyncio 框架使其异步。生成的 long_task_async 函数使用 ProcessPoolExecutor 将工作卸载到不受 GIL 约束的不同进程。
问题在于,由于某种原因,从 ProcessPoolExecutor.submit 返回的 concurrent.futures.Future 实例在从抛出 TypeError 时产生。这是设计使然吗?那些期货是否与asyncio.Future 类不兼容?什么是解决方法?
我还注意到生成器是不可提取的,因此向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())
【问题讨论】:
标签: python python-3.x python-asyncio concurrent.futures