Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 线程和条件_Python_Multithreading_Conditional Statements - Fatal编程技术网

Python 线程和条件

Python 线程和条件,python,multithreading,conditional-statements,Python,Multithreading,Conditional Statements,我是线程新手,不太了解如何使用条件。目前,我有一个线程类,如下所示: 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 =

我是线程新手,不太了解如何使用条件。目前,我有一个线程类,如下所示:

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()

这意味着我可以通过第二个线程播放一首歌曲,直到我在主线程中发出停止它的命令。我猜我必须使用locks and wait()或其他什么?

这里有一个更简单的解决方案。您正在使用Audiere库,它已经在自己的线程中播放音频。因此,不需要生成自己的第二个线程来播放音频。相反,直接从主线程使用Audiere,并从主线程停止它。

的答案可能是正确的。但也许你想使用线程的其他原因。如果是这样,您可能会发现
队列。队列
非常有用:

>>> 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\u线程
对队列执行阻塞读取,等待将命令放入队列。它会在收到命令时继续从队列中读取和打印命令,直到发出
'quit'
命令

是的,Matt,我第一次试过,只是把代码都放在主线程中。问题是当时音乐无法播放我不知道为什么。森德勒,我也试过你的解决办法。同样的问题;没有错误消息,但歌曲不会播放。