简体   繁体   English

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

[英]Stop thread execution/terminate immediately in Python 2.7

I am designing a QT based application designed in Python. 我正在设计一个使用Python设计的基于QT的应用程序。 The application has following two buttons: 该应用程序具有以下两个按钮:

  1. Move Robot 移动机器人
  2. Stop Robot 停止机器人

The robot takes some time to move from one point to another. 机器人需要一些时间才能从一个点移动到另一个点。 Hence I invoke a new thread to control robot movement to prevent the GUI from becoming unresponsive. 因此,我调用了一个新线程来控制机器人的运动,以防止GUI变得无响应。 Below the move function: 在移动功能下方:

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,))

The above function works well. 上面的功能运行良好。 In order to stop the robot motion, I need to stop the execution of the above threads. 为了停止机器人运动,我需要停止执行以上线程。 Please see the complete code below: 请查看下面的完整代码:

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

How to stop the execution of the thread? 如何停止执行线程? Any suggestions, please? 有什么建议吗?

Using a flag should be enough: 使用标志应该足够了:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM