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()
我在想什麼?
使用這種方法,我可以鏈接''start()'',就像'VideoThread(films).start()''一樣嗎? –
是的,你可以,但是如果你這樣做,你就失去了對線程的引用,這意味着你以後將無法停止它。就我個人而言,我不會這樣做。 –