【问题标题】:Make the main thread wait until all threads finish让主线程等到所有线程完成
【发布时间】:2014-10-05 03:47:10
【问题描述】:

所以我有一个线程列表,全部启动(使用threading.start()),我必须阻塞主线程列表中的所有线程完成。

这可以通过以下方式实现:

[x.join() for x in threads]

但是,对于每个x.join() 执行,所有其他线程也被阻塞。我想要的是所有线程彼此并行执行。只有当所有线程都被执行并且列表中的任何线程都不应被阻塞时,主程序才应该恢复。

据我了解,join方法不会发生我想要的,还是我错了?

【问题讨论】:

    标签: python multithreading python-2.7


    【解决方案1】:

    不,x.join() 只会阻塞主线程。其他线程继续并行执行。

    for thread in threads:
        thread.join()
    

    有点习惯用语,因为你实际上并没有建立一个列表。

    您还应该知道multithreading doesn't work as expected in Python,除非您正在执行受 IO 限制的工作(即多次访问远程服务),否则您不太可能从中获得任何性能提升。

    【讨论】:

      【解决方案2】:

      这是一个例子:

      from threading import Thread, Lock
      from time import sleep
      from random import random
      
      def target(i, lock):
          with lock:
              print("Starting thread {}".format(i))
          # Do something
          sleep(random()*5)
          with lock:
              print("Stopping thread {}".format(i))
      
      # Create the threads
      lock = Lock()
      threads = [Thread(target=target, args=(i, lock)) for i in range(5)]
      
      # Start the threads
      for x in threads:
          x.start()
      
      # Stop the threads
      for x in threads:
          x.join()
      
      print("Done!")
      

      这是一个可能的输出:

      >>>
      Starting thread 0
      Starting thread 1
      Starting thread 2
      Starting thread 3
      Starting thread 4
      Stopping thread 1
      Stopping thread 4
      Stopping thread 0
      Stopping thread 2
      Stopping thread 3
      Done!
      

      您可以看到它按您的需要工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        • 2020-09-21
        • 1970-01-01
        • 2011-06-05
        • 2019-10-24
        • 1970-01-01
        相关资源
        最近更新 更多