threading模块默认没有获取线程返回值的方法。
下面通过重写threading.Tread类来实现:
from threading import Thread
import random
import time
class MyThread(Thread):
# 继承Thread类
def __init__(self,group=None, target=None, name=None, args=(), kwargs=None, *, daemin=None):
Thread.__init__(group, target, name, args, kwargs, daemin=None)
self._return_value = None
def run(self):
# 重新定义Thread类里的run方法
try:
if self._target:
self._return_value = self._target(*args, **kwargs) # 把原来的self._target方法返回值赋给self._return_value
finally:
del self._target, self._args, self._kwargs
def join(self, timeout=None):
# 重新定义join方法,等待线程执行完成,返回值
Thread.join(self, timeout) # 调用原类的join方法,原方法中调用Thread类外方法,所以不能直接重写。
return self._return_value # 返回self._return_value,在类外,使用join获取值。
class ReturnValue(object):
# 调用自定义的thread类,获取返回值。
def __init__(self):
self.result = None
def run(self):
thread_list = []
thread_result = {}
for i in range(10)
mythread = MyThread(target=self.show, args=(i,))
thread_list.append(mythread)
mythread.start()
for t in thread_list:
self.result = t.join()
thread_result[t] = self.result
thread_list.remove(t)
for k, v thread_result.items():
print(k,v)
def show(self,i):
rand = random.randint(2,7)
time.sleep(rand)
return "args:{},rand_value:{}".format(i,rand)
return_value = ReturnValue()
return_value.run()