python多线程等待所有线程完成

标签 python multithreading

这可能是在类似的情况下被问到的,但在搜索了大约 20 分钟后我无法找到答案,所以我会问。

我已经编写了一个 Python 脚本(比如说:scriptA.py)和一个脚本(比如说 scriptB.py)

在 scriptB 中,我想用不同的参数多次调用 scriptA,每次运行大约需要一个小时,(它是一个巨大的脚本,做了很多事情......别担心),我希望能够同时使用所有不同的参数运行 scriptA,但我需要等到所有参数都完成后再继续;我的代码:

import subprocess

#setup
do_setup()

#run scriptA
subprocess.call(scriptA + argumentsA)
subprocess.call(scriptA + argumentsB)
subprocess.call(scriptA + argumentsC)

#finish
do_finish()

我想同时运行所有subprocess.call(),然后等到它们都完成,我该怎么做?

我尝试像示例 here 那样使用线程:

from threading import Thread
import subprocess

def call_script(args)
    subprocess.call(args)

#run scriptA   
t1 = Thread(target=call_script, args=(scriptA + argumentsA))
t2 = Thread(target=call_script, args=(scriptA + argumentsB))
t3 = Thread(target=call_script, args=(scriptA + argumentsC))
t1.start()
t2.start()
t3.start()

但我认为这是不对的。

在转到我的 do_finish() 之前,我怎么知道它们已经全部运行完毕?

最佳答案

将线程放在一个列表中,然后使用 Join method

 threads = []

 t = Thread(...)
 threads.append(t)

 ...repeat as often as necessary...

 # Start all threads
 for x in threads:
     x.start()

 # Wait for all of them to finish
 for x in threads:
     x.join()

关于python多线程等待所有线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11968689/

相关文章:

python - 计算每个 bin 中 numpy ndarray 的最大值

Python matplotlib/seaborn 绘图条形图子类别

java - 为不安全发布的 java.lang.String 提供恢复时间

android - Looper 还是 while 在线程中?

java - 如何检查 POJO 的字段是否 100% 线程安全?

java - 在 Android 中,如何让 Activity 在跳到下一个 Activity 之前等待?

python - 如何打印数学符号

python - 避免 Python 循环中的计数器递增

python - 在 Python 中处理数据的首选方式是什么?

c++ - 在双重检查锁定模式中获取屏障