【问题标题】:How can I set it up so that threads communicate they're complete with their task?如何设置它以便线程通信它们已完成任务?
【发布时间】:2010-10-02 18:21:25
【问题描述】:

从概念上讲,我想完成以下任务,但在理解如何在 Python 中正确编码时遇到了麻烦:

from threading import Thread
for i in range(0,3):
    t = Thread(target=myfunction)
    t.start()

# wait until threads have finished executing
print 'complete!'

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    将线程添加到列表并join()它们。

    from threading import Thread
    tlist = []
    for i in range(3):
        t = Thread(target=some_function)
        t.start()
        tlist.append(t)
    
    # wait until threads have finished executing
    for t in tlist:
        t.join()
    
    print 'complete!'
    

    【讨论】:

    • 请注意,您的所有线程都使用此代码完成,您可能最终会永远阻塞。
    • @Mykroft:如果任何线程未完成,代码无论如何都会阻塞。
    【解决方案2】:

    我从未使用过 python,但我认为您正在寻找的概念是“信号量”。

    谷歌发现了这个:

    http://www.python.org/doc/2.5.2/lib/semaphore-objects.html

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      相关资源
      最近更新 更多