【问题标题】:calling a function from a thread and letting the original thread run in the background从线程调用函数并让原始线程在后台运行
【发布时间】: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


    【解决方案1】:

    不确定它是否能解决您的问题,但您最后一个线程的目标是错误的,您使用 self 而不是 d 来调用您的 listen 实例。

    这是您的代码更正以替换上下文:

        if a in music:
            print("playing music")
            t3 = threading.Thread(target=d.playmusicobject.play)
            t3.start()
    

    注意:评论可能没问题,但没有足够的代表。

    编辑:现在明确提到重用 OP 的上下文代码。 (虽然这很明显)

    EDIT2:你在哪里调用你的第三个线程不清楚,但似乎不太好,请参阅 cmets。

    【讨论】:

    • 您确实从我的问题中获取了代码并将其作为答案引入,而我使用self.playmusicobject.play 的原因是因为播放功能在不同的类中。注意:投反对票可能是最好的,但很抱歉没有足够的代表
    • 正如我在回答中所说,您在代码中使用 self 而不是实例名称 d。我更正了这一点,并将您的代码重新用于上下文。我还提到我无法评论您的答案,而且它会比单独的答案更好。我会编辑,所以它更明确,但请注意细节。
    • 此外,我不确定从您的班级中启动一个线程(如果这是您的建议)是一个好主意,因为您在第一种方法中使用了threadLock。
    猜你喜欢
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    相关资源
    最近更新 更多