在 Python 的多线程中,有时候我们会需要每一个线程中返回的结果。
然而,在经过我的多番尝试、以及网上各种博客显示,在 Python3 中是无法获得单个线程中返回的结果的,因此我们需要定义一个类来实现这个过程,这个类的定义如下:
class MyThread(threading.Thread):
def __init__(self, func, args = ()):
super(MyThread, self).__init__()
self.func = func
self.args = args
def run(self):
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result
except Exception:
return None
然后我们就可以通过调用这个类里的函数,get_result() 来获取每个线程中返回的结果了,以下是一个测试的实例,多线程调用一个相加的函数,经过实验,是能够获取到所有线程返回的结果的。
import threading
class MyThread(threading.Thread):
def __init__(self, func, args = ()):
super(MyThread, self).__init__()
self.func = func
self.args = args
def run(self):
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result
except Exception:
return None
def add(num):
result = num + 5
return result
if __name__ == '__main__':
data = []
threads = []
nums = [1, 2, 3]
for num in nums:
t = MyThread(add, args = (num, ))
threads.append(t)
t.start()
for t in threads:
t.join()
data.append(t.get_result())
print(data)