【发布时间】:2020-11-08 11:42:45
【问题描述】:
需要帮助将对象传递给cpu_bound 函数。该程序同时使用 asyncio 和 multiprocessing,所以如果您两者都知道,那将是最好的帮助!
基本上问题出在:result = loop.run_in_executor(pool, lambda: cpu_bound(list1, list2, int_var)
我无法将 lambda 函数传递到池中,并且程序错误:_pickle.PicklingError: Can't pickle <function <lambda> at 0x00000230FDEDD700>: attribute lookup <lambda> on __main__ failed
这是我的程序的模拟结构,因为整个程序有 2000 多行代码:
import ...
# Defining some functions...
.
def cpu_bound(list1, list2, int_var):
# Some CPU-bound calculations...
.
async def find_trades(session, list3, list4):
# Some async function calls
.
with concurrent.futures.ProcessPoolExecutor() as pool:
result = loop.run_in_executor(
pool, dill.loads(dill.dumps(lambda: cpu_bound(list1, list2, int_var)))
try:
await asyncio.wait_for(
result, timeout=5
)
except asyncio.TimeoutError:
print("Took to long to compute!")
async def run():
# Some async function calls
.
await asyncio.gather(find_trades(session, list3, list4), ...)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
loop.close()
不幸的是,我对多处理相对较新,可能不知道很多关于将对象从主程序循环传递到它的多处理部分所带来的限制。
非常感谢所有帮助!
【问题讨论】:
标签: python asynchronous multiprocessing python-asyncio python-multiprocessing