2017-02-12 67 views
0

子類我試圖創建threading.Thread其方法有螺紋的子類。我將它用於視頻,但我懷疑一個工作示例對於人們通常是有用的。擴展(停止的)螺紋螺紋方法

我意識到在這裏,我從來沒有實例化一個線程,從來沒有叫start()方法,但我不知道在哪裏把它從或怎麼稱呼。我還想保存線程句柄,以便在收到stop()信號時停止。

import threading 

class VideoThread(threading.Thread): 
    """Thread class with a stop() method. The thread itself checks 
    regularly for the stopped() condition.""" 

    def __init__(self, playlist=None): 
     super(VideoThread, self).__init__() 
     self._stop = threading.Event() 
     self._player_pgid_list = [] 
     if playlist: 
      self.start_sequence(playlist) 

    def stop(self): 
     self._stop.set() 

    def stopped(self): 
     return self._stop.isSet() 

    def start_sequence(self, playlist): 
     if not isinstance(playlist, list): 
      raise ValueError("Expecting a list") 
     for video in playlist: 
      if not self.stopped(): 
       self.__start_video__(video) 

    def __start_video__(self, video): 
     if not isinstance(video, dict): 
      raise ValueError("Expecting a dictionary of video data") 
     # start the video 
     # store the video pgid so we can kill it if we have to 
     # tight wait loop to check for stopped condition 
     # kill all video(s) if necessary using the stored pgids 

類作品儘可能去,但當然,沒有一個方法實際上是線程。

start_sequence()是公開的,所以我可以這樣開始的視頻螺紋順序:

video = VideoThread() 
video.start_sequence([films[1], films[3], films[2]]) 

或當我實例化類是這樣的:

video = VideoThread([films[1], films[3], films[2]]) 

以後,如果我需要停下來,我可以:

video.stop() 

我在想什麼?

回答

1

您應該將start_sequence方法重命名爲run並刪除playlist參數(改爲使用self.playlist)。另外,刪除__init__方法中的最後兩行。我的意思是:

class VideoThread(threading.Thread): 


    def __init__(self, playlist=None): 
     super().__init__() 
     self._stop = threading.Event() 
     self._player_pgid_list = [] 
     self.playlist = playlist 

    def run(self): 
     if not isinstance(self.playlist, list): 
      raise ValueError("Expecting a list") 
     for video in self.playlist: 
      if not self.stopped(): 
       self.__start_video__(video) 

    ... 

然後,用你的類只是做:

playlist = VideoThread(films) 
playlist.start() 

,並且可以使用其停止:

playlist.stop() 

注意,當你調用.start,它調用run方法在一個單獨的控制線程中,請檢查official documentation以獲取更多信息。

+0

使用這種方法,我可以鏈接''start()'',就像'VideoThread(films).start()''一樣嗎? –

+0

是的,你可以,但是如果你這樣做,你就失去了對線程的引用,這意味着你以後將無法停止它。就我個人而言,我不會這樣做。 –