python多线程等待所有线程完成 [英] python multithreading wait till all threads finished
问题描述
这可能是在类似的情况下被问到的,但我在搜索了大约 20 分钟后找不到答案,所以我会问.
This may have been asked in a similar context but I was unable to find an answer after about 20 minutes of searching, so I will ask.
我已经编写了一个 Python 脚本(可以说:scriptA.py)和一个脚本(可以说是 scriptB.py)
I have written a Python script (lets say: scriptA.py) and a script (lets say scriptB.py)
在 scriptB 中,我想用不同的参数多次调用 scriptA,每次运行大约需要一个小时,(它是一个巨大的脚本,做了很多事情......别担心),我希望能够同时运行带有所有不同参数的 scriptA,但我需要等到所有参数都完成后再继续;我的代码:
In scriptB I want to call scriptA multiple times with different arguments, each time takes about an hour to run, (its a huge script, does lots of stuff.. don't worry about it) and I want to be able to run the scriptA with all the different arguments simultaneously, but I need to wait till ALL of them are done before continuing; my code:
import subprocess
#setup
do_setup()
#run scriptA
subprocess.call(scriptA + argumentsA)
subprocess.call(scriptA + argumentsB)
subprocess.call(scriptA + argumentsC)
#finish
do_finish()
我想同时运行所有的subprocess.call()
,然后等待它们全部完成,我该怎么做?
I want to do run all the subprocess.call()
at the same time, and then wait till they are all done, how should I do this?
我尝试像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()
之前,我怎么知道它们都已完成运行?
How do I know they have all finished running before going to my do_finish()
?
推荐答案
您需要使用 Thread对象的noreferrer">join方法.
You need to use join method of Thread
object in the end of the script.
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()
t1.join()
t2.join()
t3.join()
这样主线程会一直等到t1
、t2
和t3
执行完毕.
Thus the main thread will wait till t1
, t2
and t3
finish execution.
这篇关于python多线程等待所有线程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!