python multithreading等到所有线程完成 [英] 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?
我尝试在示例此处 a>:
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()
但是我认为这是不对的.
But I do not think this is right.
我怎么知道他们都已经完成运行才能进入我的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 multithreading等到所有线程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!