【问题标题】:Multiprocessing python function that calls a function that returns a value调用返回值的函数的多处理python函数
【发布时间】:2020-06-17 21:58:01
【问题描述】:

我正在尝试并行化我的代码,但我不知道如何正确执行。 我的代码是这样的:

import my_module

def task(i):
    result = my_module.func(i) #This takes about 30 secs
    return result

if __name__ == "__main__":
    from concurrent.futures import ProcessPoolExecutor
    executor = ProcessPoolExecutor()
    results = executor.map(task, range(500))
    print(results)

但是主程序不会等待my_module.func() 的结果。 返回类似:生成器对象_chain_from_iterable_of_lists at 0x.....

如何让进程等待func()的结果

【问题讨论】:

    标签: python concurrency process


    【解决方案1】:

    你不能,原因如下:

    多处理/线程的整个想法是,您可以在该函数中执行所有必要的代码,而不是在返回语句上等待,并且使用线程,每秒执行多次。

    也就是说,如果您需要它来等待返回数据,那么也许您不应该使用线程。但是,如果您绝对需要使用线程,则在函数本身中合并您使用返回数据的任何内容。

    【讨论】:

    • 有什么方法可以加快这样的过程吗?我需要执行该功能大约 5000 次。我可以使用更多的计算机内核吗?在没有多处理的情况下运行代码仅使用 1 个核心。
    猜你喜欢
    • 2021-07-19
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2015-08-25
    • 1970-01-01
    相关资源
    最近更新 更多