线程与条件

3 投票
2 回答
521 浏览
提问于 2025-04-16 20:17

我刚接触线程,还是不太明白怎么用条件。现在,我有一个这样的线程类:

class MusicThread(threading.Thread):
    def __init__(self, song):
        threading.Thread.__init__(self)
        self.song = song
    def run(self):
        self.output = audiere.open_device()
        self.music = self.output.open_file(self.song, 1)
        self.music.play()
        #i want the thread to wait indefinitely at this point until
        #a condition/flag in the main thread is met/activated

在主线程中,相关的代码是:

music = MusicThread(thesong)
music.start()

我的意思是,我可以通过辅助线程播放一首歌,直到在主线程中发出停止的命令。我在想,是不是得用锁和wait()之类的东西?

2 个回答

2

Matt Campbell的回答可能是对的。不过,也许你想用线程是出于其他原因。如果是这样的话,你会发现 Queue.Queue 非常有用:

>>> import threading
>>> import Queue
>>> def queue_getter(input_queue):
...     command = input_queue.get()
...     while command != 'quit':
...         print command
...         command = input_queue.get()
... 
>>> input_queue = Queue.Queue()
>>> command_thread = threading.Thread(target=queue_getter, args=(input_queue,))
>>> command_thread.start()
>>> input_queue.put('play')
>>> play
input_queue.put('pause')
pause
>>> input_queue.put('quit')
>>> command_thread.join()

command_thread 会在队列上进行阻塞读取,也就是说它会一直等着,直到有命令放到队列里。它会不断地读取并打印从队列中收到的命令,直到收到 'quit' 命令为止。

3

这里有一个更简单的解决办法。你正在使用Audiere这个库,它本身就能在自己的线程中播放音频。所以,你不需要再自己创建一个新的线程来播放音频。相反,你可以直接在主线程中使用Audiere来播放音频,并且也可以在主线程中停止它。

撰写回答