如何等到所有线程完成工作? [英] How to wait till all threads finish their work?
问题描述
我有以下脚本(不要参考内容):
I have the following script (don't refer to the contents):
import _thread
def func1(arg1, arg2):
print("Write to CLI")
def verify_result():
func1()
for _ in range (4):
_thread.start_new_thread(func1, (DUT1_CLI, '0'))
verify_result()
我想并发执行(比如 4 个线程)func1(),在我的例子中,它包括一个可能需要时间来执行的函数调用.然后,只有在最后一个线程完成其工作后,我才想执行 verify_result().
I want to concurrently execute (say 4 threads) func1() which in my case includes a function call that can take time to execute. Then, only after the last thread finished its work I want to execute verify_result().
目前,我得到的结果是所有线程都完成了他们的工作,但是 verify_result() 在所有线程完成他们的工作之前执行.
Currently, the result I get is that all threads finish their job, but verify_result() is executed before all threads finish their job.
我什至尝试在 for 循环下使用以下代码(当然我导入了线程)但没有完成工作(不要参考参数)
I have even tried to use the following code (of course I imported threading) under the for loop but that didn't do the work (don't refer to the arguments)
t = threading.Thread(target = Enable_WatchDog, args = (URL_List[x], 180, Terminal_List[x], '0'))
t.start()
t.join()
推荐答案
你的最后一个 threading
例子很接近,但你必须收集一个列表中的线程,一次启动它们,然后等待让他们一次性完成.这是一个简化的示例:
Your last threading
example is close, but you have to collect the threads in a list, start them all at once, then wait for them to complete all at once. Here's a simplified example:
import threading
import time
# Lock to serialize console output
output = threading.Lock()
def threadfunc(a,b):
for i in range(a,b):
time.sleep(.01) # sleep to make the "work" take longer
with output:
print(i)
# Collect the threads
threads = []
for i in range(10,100,10):
# Create 9 threads counting 10-19, 20-29, ... 90-99.
thread = threading.Thread(target=threadfunc,args=(i,i+10))
threads.append(thread)
# Start them all
for thread in threads:
thread.start()
# Wait for all to complete
for thread in threads:
thread.join()
这篇关于如何等到所有线程完成工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!