首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Concurrent.Futures ProcessPool Executor错误输出

Python Concurrent.Futures ProcessPool Executor错误输出
EN

Stack Overflow用户
提问于 2021-10-07 15:49:55
回答 1查看 53关注 0票数 1

我正在尝试使用ProcessPoolExecutor()来运行一些函数,但是我无法理解如何从with中获取函数的返回。

代码语言:javascript
复制
 def threaded_upload(i):
    time.sleep(2)
    if i == 0:
        k = 10
    elif i == 2:
        k = i*i
    else:
        k = -99
    return [k]

 def controller():
    if __name__ == "__main__":
        futures = []
        with ProcessPoolExecutor() as pool:
            for paso in range(4):
                futuro_i = pool.submit(threaded_upload,paso)
                wth=[futuro_i.result()]
                futures.append(futuro_i)

            wait(futures, return_when=ALL_COMPLETED)

            merged_list = []
            for future in futures:
                for valor in future.result():
                    merged_list.append(valor)
            Lista_Final = merged_list
            wait(futures, return_when=ALL_COMPLETED)
        return Lista_Final

  print(controller())

代码的输出是: None 10,-99,4,-99

我不知道为什么?“等待”似乎也不会等到所有函数都执行完。

老实说,我已经读了几天了,但对concurrent.futures或多进程的描述比我目前的知识更高级。

任何澄清都将不胜感激。提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-10-16 08:47:29

首先提交作业,然后等待结果。也可以返回整数而不是list,然后跳过内部loop

test.py:

代码语言:javascript
复制
import random
import time

from concurrent.futures import ProcessPoolExecutor, wait


def worker(i):
    t = random.uniform(1, 5)

    print(f"START: {i} ({t:.3f}s)")

    time.sleep(t)

    if i == 0:
        k = 10
    elif i == 2:
        k = i * i
    else:
        k = -99

    print(f"END: {i}")

    return k


def main():
    futures = []

    with ProcessPoolExecutor() as pool:
        for i in range(4):
            future = pool.submit(worker, i)
            futures.append(future)

        results = []

        done, pending = wait(futures) # ALL_COMPLETED is the default value

        for future in done:
            results.append(future.result())

        print(results)


if __name__ == "__main__":
    main()

测试:

代码语言:javascript
复制
$ python test.py
START: 0 (1.608s)
START: 1 (1.718s)
START: 2 (1.545s)
START: 3 (1.588s)
END: 2
END: 3
END: 0
END: 1
[10, -99, 4, -99]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69484176

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档