Python多线程(重写Thread使其可以带返回值)
threading.Thread多线程,默认是没有返回值的
如果需要返回每个线程的返回值,就需要重写函数
import threading import time 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 # 如果子线程不使用join方法,此处可能会报没有self.result的错误 except Exception: return None if __name__ == '__main__': def foo(a,b,c): time.sleep(1) return a*2,b*2,c*2 st = time.time() li = [] #线程组 for i in range(4): t = MyThread(foo,args=(i,i+1,i+2)) li.append(t) t.start() for t in li: t.join() print(t.get_result()) et = time.time() print(et - st)