线程 SpeechRecognition 并在同时做其他事情的同时获得 return 值

Thread SpeechRecognition and get return value while doing other stuff at the same time

我的问题是如何线程化一个需要时间执行的函数,然后 return 一个值,同时我可以同​​时做其他事情。

我看到其他类似的问题和解决方案,但我不知道如何在这里应用它们。

import speech_recognition as sr
r = sr.Recognizer()

import threading
from queue import Queue

queue = Queue()

def mySpeechRecognizer():

    print("START SPEECH INPUT\n") #

    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
            
        try:
            audio = r.listen(source)#, timeout = 5)  #####
            userInput = r.recognize_google(audio)
                
            if any(userInput) == True:
                print("Text Input :", userInput) #

                # do sth here
                
                print("END SPEECH INPUT NORMAL") #

                return userInput #
                    
        except Exception as e:
            print("Exception In Function mySpeechRecognizer() :", e)
                    
            print("END SPEECH INPUT EXCEPTION") #

            return #

recognize = threading.Thread(target = lambda q: q.put(mySpeechRecognizer()), args = (queue, ))
recognize.start()

print('do sth')

recognize.join()

print('do sth')

print(queue.get())

print('do sth')

我的期望是它在识别时会打印 3 次“do sth”。完成后,它将打印 return 值而不阻塞 print ,即在 print

时获取 queue.get()

我怎样才能完成这个,我的尝试有什么问题?

我想我终于想出了一个解决办法。 . .

我们可以使用 queue.empty() 检查 func 是否有 return 值( True --> 为空,即没有 return val ;False --> 不为空,即有 return val ) 所以当 queue.empty() 仍然是 True 时,我可以做其他事情,比如 print。使用 while loop ,它将是这样的:

...

while queue.empty():    # don't have return val
    print("do sth")     # do stuff

else:                   # --> have return val
    print(queue.get())  # print the return val of the func
    recognize.join()    # join the thread

如果我错了请纠正我?