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

时间:2017-11-18 07:40:06

标签: python multithreading qt pyqt

我正在设计一个用Python设计的基于QT的应用程序。该应用程序有以下两个按钮:

  1. 移动机器人
  2. 停止机器人
  3. 机器人需要一些时间从一个点移动到另一个点。因此,我调用一个新线程来控制机器人的移动,以防止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
    

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

1 个答案:

答案 0 :(得分:0)

使用标志就足够了:

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