1

所以我得到了 2 个 .py 文件,并试图将测试函数从第一个导入到第二个。但是每次我尝试时,我都会得到一个“BrokenProcessPool:进程池中的一个进程在未来正在运行或挂起时突然终止。” 错误。我不知道我搞砸了帮助非常感谢

并行.py:

import time
from concurrent import futures


def test(t):
    time.sleep(t)
    print("Ich habe {} Sekunden gewartet. Zeit {:.0f}".format(t, time.time()))



def main():
    print("Startzeit:                         {:.0f}".format(time.time()))
    start = time.perf_counter()
    with futures.ThreadPoolExecutor(max_workers=3) as ex:
        ex.submit(test, 9)
        ex.submit(test, 4)
        ex.submit(test, 5)
        ex.submit(test, 6)

        print("Alle Aufgaben gestartet.")

    print("Alle Aufgaben erledigt.")

    finish = time.perf_counter()

    print("Fertig in ",round(finish-start,2)," seconds(s)")


 
if __name__ == "__main__":
    main()
    

并行2.py:

import parallel
import time
import concurrent.futures

# =============================================================================
# def test(t):
#     time.sleep(t)
#     return ("Ich habe {} Sekunden gewartet. Zeit {:.0f}".format(t, time.time()))
# =============================================================================

def main():  
    print("Startzeit:                         {:.0f}".format(time.time()))

    start = time.perf_counter()
    
    with concurrent.futures.ProcessPoolExecutor() as executor:
        f1 = executor.submit(parallel.test, 9)
        f2 = executor.submit(parallel.test, 5)
        f3 = executor.submit(parallel.test, 4)
        f4 = executor.submit(parallel.test, 6)
        print(f1.result())
        print(f2.result())
        print(f3.result())
        print(f4.result())
 
    finish = time.perf_counter()

    print("Fertig in ",round(finish-start,2)," seconds(s)")    
    
if __name__ =="__main__":
    main()
4

1 回答 1

0

测试该解决方案:

if __name__ == "__main__"从 parallel.py 中删除一个条件。

您将条件放在两个脚本中:if __name__ == "__main__"执行 main 函数。

执行此操作时,您的脚本会检查它是否是主模块,并且仅当返回为真时才执行该函数。

当您导入另一个脚本时,您的模块不再是“ __main__”,因此返回不满足函数运行所施加的条件。.

于 2020-07-06T02:21:36.050 回答