python - 如何等待python中动态启动的多个线程完成

标签 python multithreading python-multithreading

我在 python 中使用 threading 来动态生成多个线程。这就是我生成线程的方式:

def func(max_val):

    for val in range(0,max_val):
        thread1 = threading.Thread(target=func9, args=(val,))
        thread1.start()

    print 'Ended all threads' #this should get printed once all the threads have ended
    # bunch of other code after this
    .
    .
    .


if __name__ == '__main__':
    ret = func()

我想要的是,一旦所有线程都被生成,那么进程应该等到所有线程都结束,然后继续执行代码中的下一行。我知道我们使用 thread1.join() 来等待一个线程,但是如果我将它放在 for 循环中,那么它将等待第一个线程结束,然后再生成下一个线程。我不希望它在开始下一个线程之前等待一个线程结束。它应该同时生成所有线程,然后等待所有线程结束,然后再执行下一行代码(比如上面 func() 中的 print 应该执行一次)线程已结束)。

我该怎么做?

最佳答案

为什么不把它们放在一个列表中?

threads = []

for val in range(0,max_val):
    thread1 = threading.Thread(target=func9, args=(val,))
    thread1.start()
    threads.append(thread1)

for thread in threads:
    thread.join()

关于python - 如何等待python中动态启动的多个线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31305164/

相关文章:

python - 使用后台线程定期刷新字段的值

python - 使用tensorflow和keras的不同训练结果

python线程不会死

python - 子进程的 ipython 笔记本输出

python - 在elasticsearch-py中索引特殊的JSON文件?

c# - 线程 - 如何通过 UI 交互终止工作/后台线程

java - 线程问题 - 接收方在发送方之前打印

ruby-on-rails - 在 ruby​​ 中通过并行处理有序插入数据

断言变量是 threading._Event protected 类实例

Python线程问题,raw_input()阻塞线程,线程失控