为什么并发.futures.thread的代码跳过小部件操作?

问题描述 投票:0回答:1

目标是首先对小部件执行操作(创建Button_1并删除Button_2),然后启用语音识别。] >>

我绝对应该使用current.futures.thread模块。

[在此尝试中,编译器遍历了每一行,这可以通过标有#for test注释的行的输出来证明。 问题:语音识别有效,但是仅在从函数voiceRecognition中退出后,才进行带有按钮的操作(创建Button_1和删除Button_2)。

def someFunc(self, event):
    print('Interface change started') #for test
    #creates Button_1
    #deletes config.Button_2 (from another func)
    print('Interface change finished') #for test

    with ThreadPoolExecutor(max_workers=5) as executor:
        fut = executor.submit(self.voiceRecognition)

def voiceRecognition (self):
    print('Voice recognition was started') #for test
    r = sr.Recognizer()
    with sr.Microphone(device_index=1) as sourse:
        audio = r.listen(sourse)
        query = r.recognize_google(audio)
        print(query.lower())
        print('Voice recognition was finished') #for test

输出:

Interface change started
Interface change finished
Voice recognition started
Voice recognition finished

在这里,和按钮一样(与上下文分开,它们可以正常工作,并且可以正常工作:):

config.Button_1 = wx.Button(self)
self.Bind(wx.EVT_BUTTON, self.eventFunc, Button_1)
config.Button_2.Destroy()

[帮助我了解问题的原因及其实际解决方案。谢谢。

目标是首先对小部件执行操作(创建Button_1并删除Button_2),然后启用语音识别。我绝对应该使用parallel.futures.thread模块。在此...

您遇到的问题是

1。您只为语音识别功能调用一个线程,该线程仅运行一次

  1. 我的第二个猜测是这些函数不是I / O绑定函数

线程的工作方式是另一个函数在前一个函数正在等待接收特定数据或类似内容时启动。如果没有这样的要求,则线程不是很有用enter image description here

第二个功能开始运行的点是第一个功能等待接收某些资源的点。如果这不是您的要求,则可能需要研究多处理或异步/等待功能(使用asyncio包)

import asyncio

async def someFunc(event):
    print('Interface change started') #for test
    #creates Button_1

    await event() #when code runs with voiceRecognition past as the event parameter, that is what will run here

    #deletes config.Button_2 (from another func)
    print('Interface change finished') #for test

def voiceRecognition ():
    print('Voice recognition was started') #for test
    r = sr.Recognizer()
    with sr.Microphone(device_index=1) as sourse:
        audio = r.listen(sourse)
        query = r.recognize_google(audio)
        print(query.lower())
        print('Voice recognition was finished') #for test

 asyncio.run(someFunc(voiceRecognition)) #to run it asynchronously

我真的不知道您的类看起来如何,因此我将其编写为典型函数,这意味着您将不得不对其稍作调整以适合您的代码。

注意使用[[event

参数更改在voiceRecognition()中调用someFunc的方式,并且还要注意现在在someFunc中调用了位置事件
python concurrent.futures
1个回答
0
投票

您遇到的问题是

1。您只为语音识别功能调用一个线程,该线程仅运行一次

© www.soinside.com 2019 - 2024. All rights reserved.