代码之家  ›  专栏  ›  技术社区  ›  Nick Stinemates

我该如何设置它,以便线程通信它们已经完成了任务?

  •  0
  • Nick Stinemates  · 技术社区  · 17 年前

    从概念上讲,我想完成以下任务,但很难理解如何在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!'
    
    2 回复  |  直到 17 年前
        1
  •  6
  •   nosklo    17 年前

    将线程添加到列表中,然后 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!'
    
        2
  •  -4
  •   E.J. Brennan    17 年前

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

    谷歌发现了这个:

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