Python线程无法作为后台/并行任务运行问题求助
问题诊断与修复方案
核心错误原因
你创建线程时犯了关键错误:target参数传入的是函数调用结果(比如trackLocation()),而非函数对象(trackLocation)。Python遇到trackLocation()会立刻在当前主线程执行该函数,进入while True死循环,导致后续代码完全无法运行,和普通函数调用的表现完全一致。
修复步骤
1. 修正线程创建的target参数
把target=trackLocation()改为target=trackLocation,去掉括号,让线程明确要执行的是这个函数本身,而非立刻调用它。
2. 修复测试菜单的逻辑错误
你的threadTest函数里,choice == '0'是比较操作,不是赋值,应改为choice = '0',这样才能回到循环等待下一次输入。
3. 简化测试代码的额外修复
简化测试代码里的threadTest函数没有更新全局变量cx和cy,需要在循环内添加赋值语句;同时同样要修正线程创建的target参数。
修正后的代码示例
位置追踪功能的修正代码
import threading import time # 假设robot和bosdyn相关模块已提前导入 # 初始化全局位置变量 currentX = 0.0 currentY = 0.0 # Location Stuff def trackLocation(): global currentX global currentY xList =[] yList = [] while True: test = robot.get_frame_tree_snapshot() transform = bosdyn.client.frame_helpers.get_vision_tform_body(test) xT = transform.transform_point(0, 0, 0) x, y, z = xT xList.append(x) yList.append(y) currentX = x currentY = y print(currentX, currentY) time.sleep(2.0) def threadTest(): choice = '0' while choice == '0': choice = input("Enter number of selection: ") if choice == '1': print("please work", currentX, currentY) choice = '0' # 修正:赋值而非比较 # 修正线程创建方式 t = threading.Thread(target=trackLocation, daemon=True) t.start() threadTest()
简化测试代码的修正版本
import time import threading import sys # 初始化全局变量 cx = 0 cy = 0 def threadTest(): global cx global cy x = 1 y = 2 while True: x += 1 y += 1 cx = x # 更新全局变量 cy = y time.sleep(2.0) def threadChoice(): choice = '0' while choice == '0': choice = input("Enter number of selection: ") if choice == '1': print("please work", cx, cy) choice = '0' # 修正:赋值而非比较 def main(argv): # 修正线程target参数,去掉括号 t = threading.Thread(target=threadTest, args=()) t.start() threadChoice() if __name__ == '__main__': if not main(sys.argv[1:]): sys.exit(1)
额外建议
- 尽量减少全局变量的使用,可考虑用线程安全的容器(比如
queue.Queue)或者自定义类来存储位置信息,避免多线程下的潜在问题。 - 如果需要优雅停止后台线程,可以设置一个全局的停止标志(比如
running = True),在主线程需要退出时将其设为False,后台线程的while循环改为while running:。
内容的提问来源于stack exchange,提问作者Sam Dean
相关产品推荐
相关产品推荐

