python获得子线程的返回值

[python]  view plain  copy
  1. import sys  
  2. import threading  
  3. import Queue  
  4. q = Queue.Queue()  
  5. def worker1(x, y):  
  6.     func_name = sys._getframe().f_code.co_name  
  7.     print "%s run ..." % func_name  
  8.     q.put((x + y, func_name))  
  9. def worker2(x, y):  
  10.     func_name = sys._getframe().f_code.co_name  
  11.     print "%s run ...." % func_name  
  12.     q.put((x - y, func_name))  
  13. if __name__ == '__main__':  
  14.     result = list()  
  15.     t1 = threading.Thread(target=worker1, name='thread1', args=(105, ))  
  16.     t2 = threading.Thread(target=worker2, name='thread2', args=(201, ))  
  17.     print '-' * 50  
  18.     t1.start()  
  19.     t2.start()  
  20.     t1.join()  
  21.     t2.join()  
  22.     while not q.empty():  
  23.         result.append(q.get())  
  24.     for item in result:  
  25.         if item[1] == worker1.__name__:  
  26.             print "%s 's return value is : %s" % (item[1], item[0])  
  27.         elif item[1] == worker2.__name__:  
  28.             print "%s 's return value is : %s" % (item[1], item[0])  

这是目前最主流的获取线程数据的方法。使用 Queue 库创建队列实例,用来储存和传递线程间的数据。Python 的队列是线程安全的,也就是说多个线程同时访问一个队列也不会有冲突。Python 队列有三种 FIFO 先进先出,FILO 先进后出(类似栈),优先级队列(由单独的优先级参数决定顺序)。使用队列可以实现简单 生产者 – 消费者 模型
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值