python - 如何等到所有线程完成工作?

标签 python multithreading python-3.x

我有如下脚本(不引用内容):

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()

目前,我得到的结果是所有线程都完成了他们的工作,但是 verify_result() 是在所有线程完成他们的工作之前执行的。

我什至尝试在 for 循环下使用以下代码(当然我导入了线程)但没有完成工作(不要引用参数)

t = threading.Thread(target = Enable_WatchDog, args = (URL_List[x], 180, Terminal_List[x], '0'))
t.start()
t.join()

最佳答案

您的最后一个threading 示例已经结束,但是您必须将线程收集到一个列表中,同时启动它们,然后等待它们同时完成。这是一个简化的示例:

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()

关于python - 如何等到所有线程完成工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46301933/

相关文章:

c# - 生产者消费者模式如何通知完成?

java - 在线程中运行的信号量任务

python - python中的模块化算法迭代 Pandas 数据框

python - Pandas str.extract 从字符串字段检索字典

python - 使用 Python 替换文本文件中以逗号分隔的特定列中的单词

c++ - 几个线程 : catching the moment when they all finish work

python-3.x - 如何使用 Boto3 向 AWS Batch 提交多个命令?

python3 和请求 : still getting 'sslv3 alert handshake failure'

python - PyQt 的 "pyqtProperty"VS python 的标准 "property"

python - Pyvmomi - 如何在没有安装 VMTools 的情况下获取虚拟机的 IP?