在Python 2.7中立即停止线程执行/终止

问题描述:

我正在设计一个基于QT的应用程序,它是用Python设计的。该应用程序具有以下两个按钮:在Python 2.7中立即停止线程执行/终止

  1. 移动机器人
  2. 停止机器人

机器人需要一些时间来移动从一点到另一点。因此,我调用一个新的线程来控制机器人的运动,以防止GUI无响应。移动功能下方:

from threading import Thread 
from thread import start_new_thread 

def move_robot(self): 
    def move_robot_thread(points): 
     for point in points: 
      thread = Thread(target=self.robot.move, args=(point,)) 
      thread.start() 
      thread.join() 
    start_new_thread(move_robot_thread, (points,)) 

上述功能运行良好。为了阻止机器人的运动,我需要停止执行上述线程。请参阅下面的完整代码:

from python_qt_binding.QtGui import QPushButton 

self.move_robot_button = QPushButton('Move Robot') 
self.move_robot_button.clicked.connect(self.move_robot) 
self.move_robot_button = QPushButton('Stop Robot') 
self.move_robot_button.clicked.connect(self.stop_robot) 
self.robot = RobotControllerWrapper() 

from threading import Thread 
from thread import start_new_thread 

def move_robot(self): 
    def move_robot_thread(points): 
     for point in points: 
      thread = Thread(target=self.robot.move, args=(point,)) 
      thread.start() 
      thread.join() 
    start_new_thread(move_robot_thread, (points,)) 

def stop_robot(self): 
    pass 

class RobotControllerWrapper(): 
    def __init__(self): 
     self.robot_controller = RobotController() 

    def move(self, point): 
     while True: 
      self._robot_controller.move(point) 
      current_location = self.robot_controller.location() 
      if current_location - point < 0.0001: 
       break 

如何停止执行线程?有什么建议吗?

使用标志应该足够:

self.run_flag = False # init the flag 
... 

def move_robot(self): 
    def move_robot_thread(points): 
     self.run_flag = True # set to true before starting the thread 
     ... 

def stop_robot(self): 
    self.robot.stop() 

class RobotControllerWrapper(): 
    ... 
    def move(self, point): 
     while self.run_flag == True: # check the flag here, instead of 'while True' 
      ... 

    def stop(self): 
     self.run_flag = False # set to false to stop the thread