2017-11-18 12 views
0

私はPythonで設計されたQTベースのアプリケーションを設計しています。アプリケーションは、2つのボタンが、次のい: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 

スレッドの実行を停止するにはどうすればよいですか?何か提案してください。

答えて

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 
関連する問題