python获得子线程的返回值

来源:互联网 发布:dnf钓鱼源码 编辑:程序博客网 时间:2024/06/05 16:20
import sysimport threadingimport Queueq = 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 先进后出(类似栈),优先级队列(由单独的优先级参数决定顺序)。使用队列可以实现简单 生产者 – 消费者 模型

原创粉丝点击