【问题标题】:how to wait for dynamically started multiple threads in python to finish如何等待python中动态启动的多个线程完成
【发布时间】:2023-03-11 12:30:01
【问题描述】:

我在 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 应该在所有线程结束后执行)。

我该怎么做?

【问题讨论】:

    标签: python multithreading python-multithreading


    【解决方案1】:

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

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

    【讨论】:

    • 您不应该检查thread 是否是current thread 以避免deadlock 的情况吗?
    • @KhalilAmmour-خليلعمور你在说什么僵局?
    • 来自 Python 文档:>join() 如果尝试加入当前线程,则会引发 RuntimeError,因为这会导致死锁。
    • @KhalilAmmour-خليلعمور,我其实不知道这种方式不是thread-safe。您能否将正确的方法添加为另一个答案?谢谢。
    • @Sait 发布为答案
    【解决方案2】:

    参考PythonDocs

    如果尝试加入当前的

    join(),则会引发 RuntimeError 线程,因为这会导致死锁。 join() 也是一个错误 线程在它开始之前并尝试这样做会引发 同样的例外。

    您可以这样做,甚至无需将它们保存到列表中(示例取自here):

    main_thread = threading.currentThread()
    for t in threading.enumerate():
        if t is main_thread:
            continue
        t.join()
    

    enumerate() 返回活动线程实例的列表

    【讨论】:

      猜你喜欢
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      相关资源
      最近更新 更多