我正在开发一个程序,该程序向用户显示一个名为 test 的图像(使用方法 cal_picture(test,uration))并同时跟踪他们的眼睛位置(使用方法 eyetracker(start,duration))。 这两者都会持续一段由可变持续时间决定的时间。 为了使这两个同时运行,我使用 _thread 模块将它们放入两个线程中:
import _thread
import time
start = time.time()
_thread.start_new_thread(cal_picture, (test, duration))
_thread.start_new_thread(eyetracker, (start, duration))
# Start of both threads
while (time.time() - start) < (duration + 2):
time.sleep(1)
# waiting for the threads to run through
eyetracker(start,duration)方法返回描述检测到的用户瞳孔位置的坐标列表,但是,我无法在稍后的代码中调用该列表。
我尝试将eyetracker函数返回的列表保存为一个名为positions的变量,该变量在创建线程之前被声明为一个空列表,作为参数提供给eyetracker函数并相当于它将在函数本身。然而,给予眼球追踪器函数的位置变量仅被视为眼球追踪器函数内的局部变量,并没有更改同名的全局变量(事后看来这是有意义的)。
(在眼动仪方法中:)
def eyetracker(positions, start, duration):
...
positions = returned_pupil_positions
(代码中需要瞳孔位置的部分:)
positions = []
_thread.start_new_thread(cal_picture, (test, duration))
_thread.start_new_thread(eyetracker, (positions, start, duration))
# positions is still []
接下来,我尝试将位置与为眼动追踪器创建线程的行等同,希望它能够返回眼动追踪器的返回值。然而,这也不起作用,位置被设置为一个整数值,我不知道其起源:
_thread.start_new_thread(cal_picture, (test, duration))
positions = _thread.start_new_thread(eyetracker, (start, duration))
# positions is now an integer value for some reason, even though the eyetracker method returns a list of values, which is exactly what I need positions to be
长话短说:在使用 _thread 模块运行 Eyetracker 方法后,如何使我的变量位置等于 Eyetracker 方法的返回值?
也许获得
positions
(“简单”,即需要编写的代码行数最少)的最简单方法是使用 ThreadPoolExecutor
来启动线程。当您将任务发送给执行器时,它会返回一个 submit
对象,您可以使用该对象来获取任务返回的值:
Future