我试图创建一个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()
我错过了什么?
答案 0 :(得分:1)
您应该将margin: 0 auto
方法重命名为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
方法,请查看official documentation以获取更多信息。