python线程获取返回值
- 实现功能前的准备代码
- 改写threading.Thread类获取返回值
- 使用局部变量获取返回值
实现功能前的准备代码
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()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
现在我们需要在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()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
此种方法的缺点:速度很慢,像是开了个假线程,慎用。
使用局部变量获取返回值
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()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
运用局部变量 此处一定要join,否则主线程跑完了,还可能会有一部分say_hello的返回值 未append到列表中。
此种方法的缺点:适用于返回值添加到 列表 等这种局部变量的情况,不适用获取单个返回值。