我如何杀死一个特定的线程,而不知道它的引用?

2024-04-24 01:17:49 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我让线程每10秒播放一次声音。 我还有一个settings文件,其中包含一定数量的线程设置(id,要播放的声音)。我的主脚本取消勾选每个线程设置,然后用它们自己的设置启动尽可能多的线程。你知道吗

我的问题是,如何杀死其中一个线程,而只杀死一个?不是第一个或最后一个,我想有能力选择哪一个。有可能吗?你知道吗

我考虑过给每个线程一个引用,但是由于我从settings文件中获取它们,所以我不知道需要启动多少个线程。你知道吗

声音播放线程:

class MyThread(Thread):

    def __init__(self, sound):
        Thread.__init__(self)
        self.sound = sound
        self.stopped = False

    def run(self):
        while not self.stopped:
            #Totally made up function, as an example
            playsound(self.sound)
            time.sleep(10)

    def stop(self):
        self.stopped = True

主脚本:

threads = []
with open('settings', 'rb') as f:
    while True:
        try:
            threads.append(pickle.load(f))
            continue
        except EOFError:
            break

for i in range(threads)
    #Model of threads: [id, sound], [id, sound], [id, sound]...
    MyThread(i[1]).start()

Tags: 文件self脚本id声音settingsinitdef