python thread wait until specific thread complete

#!python3.3
import queue    # For Python 2.x use 'import Queue as queue'
import threading, time, random

def func(id, result_queue):
    print("Thread", id)
    time.sleep(random.random() * 5)
    result_queue.put((id, 'done'))

def main():
    q = queue.Queue()
    threads = [ threading.Thread(target=func, args=(i, q)) for i in range(5) ]
    for th in threads:
        th.daemon = True
        th.start()

    result1 = q.get()
    result2 = q.get()

    print("Second result: {}".format(result2))

if __name__=='__main__':
    main()

Documentation for Queue.get() (with no arguments it is equivalent to Queue.get(True, None):

Queue.get([block[, timeout]])

Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).

share | edit | flag
   


 
Won't this raise an Empty exception if the Queue is empty when you do q.get()? –   Michael  Jul 10 '13 at 16:53
 
@Michael, the default for q.get() is to do a blocking get, so no it won't throw an exception instead it will block the main thread until there is a result available. –   Duncan  Jul 10 '13 at 17:43


 
Won't this raise an Empty exception if the Queue is empty when you do q.get()? –   Michael  Jul 10 '13 at 16:53
 
@Michael, the default for q.get() is to do a blocking get, so no it won't throw an exception instead it will block the main thread until there is a result available. –   Duncan  Jul 10 '13 at 17:43
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值