Python 3.x 如何暂停一个线程,直到另一个线程在python中停止其操作?
我有两个线程同时运行,Python 3.x 如何暂停一个线程,直到另一个线程在python中停止其操作?,python-3.x,multithreading,speech-recognition,pyttsx,Python 3.x,Multithreading,Speech Recognition,Pyttsx,我有两个线程同时运行,speechRecognition和speakBack。这两个线程都是在while循环中运行的(while True:#do something)。 语音识别一直在等待麦克风输入。然后,一旦收到,它将口头输入的文本版本保存到一个文件中,该文件由我的第二个线程加载,speakBack,并通过扬声器讲话。 我的问题是,当通过扬声器说出短语时,麦克风会将其拾取,然后将其翻译并再次保存到该文件中进行处理,从而导致无休止的循环 如何使speechRecognition线程挂起,等待s
speechRecognition
和speakBack
。这两个线程都是在while循环中运行的(while True:#do something
)。
语音识别一直在等待麦克风输入。然后,一旦收到,它将口头输入的文本版本保存到一个文件中,该文件由我的第二个线程加载,speakBack
,并通过扬声器讲话。
我的问题是,当通过扬声器说出短语时,麦克风会将其拾取,然后将其翻译并再次保存到该文件中进行处理,从而导致无休止的循环
如何使speechRecognition
线程挂起,等待speakBack
线程停止通过扬声器输出声音,然后继续收听下一个口头输入?
我将speechRecognition库和pyttsx3库分别用于语音识别和语音输出。实现这一点的方法是在线程之间共享状态(使用全局变量,线程可以存储和读取这些变量以指示其进度,或者使用传递到每个线程的可变引用). 我将在下面给出的解决方案涉及一个全局变量,该变量存储可变引用,但是您可以同样轻松地将队列传递到两个线程中,而不是全局存储它 在python中,使用队列是在线程之间传递消息的一种非常标准的方式,因为队列已经以线程安全的方式编写,因此您不必考虑同步和锁定。此外,对
queue.get
的阻塞调用的实现方式不会涉及重复和浪费地检查while循环中的条件变量
下面是一些代码的外观:
import queue
START_SPEAK_BACK = 0
START_SPEECH_RECOGNITION = 1
messageQueue = queue.Queue()
# thread 1
def speechRecognition():
while True:
# wait for input like you were doing before
# write to file as before
# put message on the queue for other thread to get
messageQueue.put(START_SPEAK_BACK)
# Calling `get` with no arguments makes the call be
# "blocking" in the sense that it won't return until
# there is an element on the queue to get.
messageFromOtherThread = messageQueue.get()
# logically, messageFromOtherThread can only ever be
# START_SPEECH_RECOGNITION, but you could still
# check that this is true and raise an exception if not.
# thread 2
def speakBack():
while True:
messageFromOtherThread = messageQueue.get()
# likewise, this message will only be START_SPEAK_BACK
# but you could still check.
# Here, fill in the code that speaks through the speakers.
# When that's done:
messageQueue.put(START_SPEECH_RECOGNITION)
一些评论: