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 3.x 如何暂停一个线程,直到另一个线程在python中停止其操作?_Python 3.x_Multithreading_Speech Recognition_Pyttsx - Fatal编程技术网

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)
一些评论:

  • 此解决方案使用单个队列。它可以很容易地使用两个队列,一个用于回显->语音识别通信,另一个用于语音识别->通信。如果两个线程同时生成消息,这可能更有意义

  • 这个解决方案实际上并不涉及检查消息的内容。但是,如果需要在线程之间传递附加信息,可以非常轻松地将对象或数据作为消息传递(而不仅仅是常量值)

  • 最后,我不清楚为什么不在同一个线程中运行所有代码。似乎有一系列非常清晰的步骤需要你的程序遵循:获取音频输入,将其写入文件,将其回复,重新开始。将所有内容编写为普通的、串行的、无线程的python程序可能更有意义