【发布时间】:2018-01-21 15:51:04
【问题描述】:
我从一个线程调用一个函数,一旦函数开始运行,两个线程都会停止工作,直到函数完成执行,并且在函数执行后程序停止。
class listen(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.playmusicobject = playmusic()
self.objectspeak = speak()
self.apiobject = googleAPI()
def listening(self):
self.r = sr.Recognizer()
threadLock.acquire()
try:
with sr.Microphone() as source:
print("say something")
self.audio = self.r.listen(source)
finally:
threadLock.release()
def checkingaudio(self):
threadLock.acquire()
try:
# a = str(self.r.recognize_google(self.audio))
a = str(self.r.recognize_google(self.audio))
print(a)
if a in greetings:
self.objectspeak.speaking("I am good how are you?")
if a in music:
print("playing music")
self.playmusicobject.play()
if a in stop:
print("stopping")
self.playmusicobject.b()
if a in api:
self.apiobject.distance()
finally:
threadLock.release()
class playmusic:
def play(self):
playsound.playsound("playthisfile")
if __name__ == "__main__":
while 1:
d = listen()
t1 = threading.Thread(target=d.listening)
t1.start()
t2 = threading.Thread(target=d.checkingaudio)
t2.start()
每当我在 playmusic 中调用 play 函数时,两个线程都应该停止,并且在 play 函数执行后程序停止。无论如何,函数 play 或实际上由运行 CheckingAudio 函数的线程调用的任何其他函数都不会停止 2 个原始线程。我尝试将 play 函数作为自己的线程运行,但在这样做,它只是给了我一个错误,说无法启动线程 t3,调用函数的方式是线程(这可能是错误的)
if a in music:
print("playing music")
t3 = threading.Thread(target=self.playmusicobject.play)
t3.start()
我尝试在 playmusic 类中创建一个 runplaythread 函数,但仍然给我错误无法启动线程。
【问题讨论】:
标签: python multithreading