第一种方法最常用:自定义线程类,继承Thread类
新建自定义线程类继承线程类中的run方法和join方法; 重写join方法,在调用join方法时返回结果;
伪代码如下:
from threading import Thread
def foo(someting):
return f'{someting} is result'
class returnValueThread(Thread):
def __init__(self,someargs):
''''''
Thread.__init__(self)
self.someargs = someargs
def run(self):
''''''
self.result = foo(someting=self.someargs)
def join(self):
super().join()
return self.result
mythread = returnValueThread('test')
mythread.start()
result = mythread.join()
print(result)
第二种方法可以使用python中内置的concurrent.futures库:
Python 的标准库 concurrent.futures 直接获取线程的返回值;代码量更少,推荐使用此方法;
伪代码如下:
def futuresReturnValue():
''''''
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
threads = []
for i in range(10): # 多个任务
future = executor.submit(foo, f"agrs_{i}")
threads.append(future)
for future in concurrent.futures.as_completed(threads): # 并发执行
print(future.result())
futuresReturnValue()
运行结果如下: