python获得子线程的返回值

import sys
import threading
import Queue
q = Queue.Queue()
def worker1(x, y):
	func_name = sys._getframe().f_code.co_name
	print "%s run ..." % func_name
	q.put((x + y, func_name))
def worker2(x, y):
	func_name = sys._getframe().f_code.co_name
	print "%s run ...." % func_name
	q.put((x - y, func_name))
if __name__ == '__main__':
	result = list()
	t1 = threading.Thread(target=worker1, name='thread1', args=(10, 5, ))
	t2 = threading.Thread(target=worker2, name='thread2', args=(20, 1, ))
	print '-' * 50
	t1.start()
	t2.start()
	t1.join()
	t2.join()
	while not q.empty():
		result.append(q.get())
	for item in result:
		if item[1] == worker1.__name__:
			print "%s 's return value is : %s" % (item[1], item[0])
		elif item[1] == worker2.__name__:
			print "%s 's return value is : %s" % (item[1], item[0])

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值