Python子线程获取返回值的实现方案

不晚
不晚
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍在Python中通过继承Thread类并重写run方法,将子线程的计算结果存储为实例属性,随后通过自定义get_result方法获取返回值。结合join确保线程执行完毕后再读取结果,实现子线程与主线程的数据交互。

具体实现方式如下所示:

# coding:utf-8
import time
 
from threading import Thread
 
def foo(number):
  time.sleep(20)
  return number
 
class MyThread(Thread):
 
  def __init__(self, number):
    Thread.__init__(self)
    self.number = number
 
  def run(self):
    self.result = foo(self.number)
 
  def get_result(self):
    return self.result
 
 
thd1 = MyThread(3)
thd2 = MyThread(5)
thd1.start()
thd2.start()
thd1.join()
thd2.join()
 
print thd1.get_result()
print thd2.get_result()

上述内容即为Python中从子线程获取返回值的具体方法,希望能为读者提供有价值的参考。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表