Tagc
Tagc

Reputation: 99

Threading and Conditions

I'm new to threading and I don't really understand how to use conditions. At the moment, I have a thread class like this:

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

In the main thread, the relevent code is:

music = MusicThread(thesong)
music.start()

What this should mean is that I can get a song playing through the secondary thread until I issue a command in the main thread to stop it. I'm guessing i'd have to use locks and wait() or something?

Upvotes: 3

Views: 542

Answers (2)

senderle
senderle

Reputation: 151077

Matt Campbell's answer is probably right. But maybe you want to use a thread for other reasons. If so, you may find a Queue.Queue very useful:

>>> 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 does a blocking read on the queue, waiting for a command to be put on the queue. It continues to read and print commands off the queue as they are received until the 'quit' command is issued.

Upvotes: 2

Matt Campbell
Matt Campbell

Reputation: 65

There is a much simpler solution here. You're using the Audiere library, which already plays audio in its own thread. Therefore, there is no need to spawn a second thread of your own just to play audio. Instead, use Audiere directly from the main thread, and stop it from the main thread.

Upvotes: 3

Related Questions