python线程获取返回值

实现功能前的准备代码

def say_hello(i):
    return {"hello": i}

def threading_get_return():
    vendorCode = []
    for i in range(1000):
        result = say_hello(i)
        vendorCode.append(result)

if __name__ == '__main__':
	threading_get_return()

现在我们需要在threading_get_return方法中获取返回值。
python的线程正常是获取不了返回值的,但实际应用中开线程后,需要获取返回值,以下提供两种获取返回值的方式:


改写threading.Thread类获取返回值

import threading
class MyThread(threading.Thread):

    def __init__(self, func, args):
        threading.Thread.__init__(self)
        self.func = func
        self.args = args
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result
        except Exception:
            # print(traceback.print_exc())
            return "threading result except"

#	复制以上代码 原本代码改写如下

def say_hello(i):
    return {"hello": i}

def threading_get_return():
    vendorCode = []
    for i in range(1000):
        th = MyThread(say_hello, args=(i,))
        th.start()
        th_list.append(th)        
   	
	for th in th_list:
    	th.join()
    	result = th.get_result()
        vendorCode.append(result)

if __name__ == '__main__':
	threading_get_return()

此种方法的缺点:速度很慢,像是开了个假线程,慎用。


使用局部变量获取返回值

import threading

def say_hello(i, vendorCode):
    #  return {"hello": i}
    vendorCode.append({"hello": i})

def threading_get_return():
    vendorCode = []
    for i in range(1000):
        th = threading.Thread(say_hello, args=(i, vendorCode))
        th.start()
        th_list.append(th)
        vendorCode.append(result)
   	
   	#	运用局部变量 此处一定要join
	for th in th_list:
    	th.join()

if __name__ == '__main__':
	threading_get_return()

运用局部变量 此处一定要join,否则主线程跑完了,还可能会有一部分say_hello的返回值 未append到列表中。

此种方法的缺点:适用于返回值添加到 列表 等这种局部变量的情况,不适用获取单个返回值。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值