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()''一样吗? –
是的,你可以,但是如果你这样做,你就失去了对线程的引用,这意味着你以后将无法停止它。就我个人而言,我不会这样做。 –