如何获取_thread模块中线程函数的返回值?
解决_thread模块获取线程返回值的问题
为什么你的方法行不通
- 直接赋值列表变量无效:你传入空列表
positions后,在函数里执行positions = returned_pupil_positions只是把局部变量positions重新绑定到了新的列表对象,并没有修改你传入的原列表。因为列表是可变对象,但你做的是重新赋值,不是修改对象内容。 - start_new_thread返回的是线程ID:你得到的整数其实是线程的唯一标识符,不是函数返回值,这是
_thread.start_new_thread的设计特性。
可行解决方案
方案1:修改传入的可变对象内容
利用列表的可变性,在eyetracker函数里直接修改原列表的内容,而不是重新赋值变量:
修改eyetracker函数:
def eyetracker(positions, start, duration): # 你的瞳孔检测逻辑,得到坐标列表 returned_pupil_positions = [(x1,y1), (x2,y2), ...] # 示例结果 # 用切片赋值修改原列表内容,而不是重新绑定变量 positions[:] = returned_pupil_positions
调用代码:
import _thread import time positions = [] start = time.time() # 启动两个线程 _thread.start_new_thread(cal_picture, (test, duration)) _thread.start_new_thread(eyetracker, (positions, start, duration)) # 等待线程执行完成 while (time.time() - start) < (duration + 2): time.sleep(1) # 此时positions已经被修改为瞳孔坐标列表 print(positions)
方案2:用队列存储返回值(更安全)
使用queue.Queue来传递线程结果,适合更复杂的多线程场景:
import _thread import time import queue def eyetracker(result_queue, start, duration): # 你的瞳孔检测逻辑 returned_pupil_positions = [(x1,y1), (x2,y2), ...] # 将结果放入队列 result_queue.put(returned_pupil_positions) # 创建结果队列 result_queue = queue.Queue() start = time.time() _thread.start_new_thread(cal_picture, (test, duration)) _thread.start_new_thread(eyetracker, (result_queue, start, duration)) # 等待线程执行 while (time.time() - start) < (duration + 2): time.sleep(1) # 从队列取出结果 positions = result_queue.get() print(positions)
额外建议:考虑使用threading模块
_thread是Python底层的线程模块,功能有限。如果可以切换到更易用的threading模块,可以通过自定义线程类来更优雅地获取返回值:
import threading import time class EyetrackerThread(threading.Thread): def __init__(self, start, duration): super().__init__() self.start_time = start self.duration = duration self.result = None # 用于存储返回值 def run(self): # 你的瞳孔检测逻辑 self.result = [(x1,y1), (x2,y2), ...] # 启动线程 start = time.time() pic_thread = threading.Thread(target=cal_picture, args=(test, duration)) eye_thread = EyetrackerThread(start, duration) pic_thread.start() eye_thread.start() # 等待线程结束 pic_thread.join() eye_thread.join() # 获取结果 positions = eye_thread.result
内容的提问来源于stack exchange,提问作者Marissa
相关产品推荐
相关产品推荐

