Python多线程输出存变量报错:'Thread'对象无'result'属性
问题排查与解决
直接错误原因
Python标准库的threading.Thread类没有result()方法,这是报错的核心原因。另外你的代码还有两个隐藏问题:
- 创建线程时,
target = job(R003_file_List[0:4])是直接调用了job函数,而非将函数作为线程执行目标,这会导致job在主线程同步执行,线程根本没起到并发作用。 - 第二个线程变量名写错:定义了
thread12,却调用thread2.start(),会引发NameError。
解决方法
方法1:用全局变量存储线程返回值
利用线程共享进程内存空间的特性,用全局变量接收job的返回结果:
import threading # 定义全局变量存结果 output_1 = None output_2 = None def job(file_list): # 原job逻辑,最后返回结果 ... return Capex_date_DF def thread_func_1(): global output_1 output_1 = job(R003_file_List[0:4]) def thread_func_2(): global output_2 output_2 = job(R003_file_List[5:8]) # 创建并启动线程 thread1 = threading.Thread(target=thread_func_1) thread2 = threading.Thread(target=thread_func_2) thread1.start() thread2.start() thread1.join() thread2.join() # 此时output_1和output_2已被赋值 print(output_1, output_2)
方法2:自定义带返回值的线程类
继承threading.Thread,重写run方法,把结果存在实例属性中:
import threading class ResultThread(threading.Thread): def __init__(self, target, args=()): super().__init__() self.target = target self.args = args self.result = None def run(self): self.result = self.target(*self.args) # 创建线程,传入job函数和参数 thread1 = ResultThread(target=job, args=(R003_file_List[0:4],)) thread2 = ResultThread(target=job, args=(R003_file_List[5:8],)) thread1.start() thread2.start() thread1.join() thread2.join() # 通过实例的result属性获取返回值 output_1 = thread1.result output_2 = thread2.result
方法3:用concurrent.futures.ThreadPoolExecutor(推荐)
Python3.2+自带的模块,专门处理并发任务,能直接获取返回值,写法更简洁:
from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=2) as executor: # 提交任务到线程池 future1 = executor.submit(job, R003_file_List[0:4]) future2 = executor.submit(job, R003_file_List[5:8]) # 获取任务结果 output_1 = future1.result() output_2 = future2.result()
内容的提问来源于stack exchange,提问作者CanaryTheBird
相关产品推荐
相关产品推荐

