我正在用Python做一个虚拟助手。为此,我需要一个主线程连续运行,这是语音识别所必需的,并希望在检测到语音后运行其他线程,比如在后台运行。
对于像timer这样的任务,我想让它在主线程运行时在后台运行,这样即使在计时器运行时,我也可以执行其他任务。到达时间后,它应该以tts的形式返回到主线程
我现在使用的结构是
main.py -> class Main() ->Running logger in background // which is meant to exit with mainLoop -> and Command() loop for speech recognition continuously ->`which链接到Brain.py到timer.py
发布于 2017-12-25 08:05:18
关于multithreading与multiprocessing的几句话:
在multithreading中,您在当前进程中启动一个线程。Python以短的顺序运行(通过global interpreter lock)线程,从来没有真正并行。好处是线程可以访问相同的变量(即共享内存)。
另一方面,在multiprocessing中,您运行一个新进程(在操作系统中,它显示为一个单独的程序)。它们确实可以并行运行,但是共享变量要复杂得多(而且速度也要慢得多)。
对于您的用例,似乎没有两件事是"CPU绑定“的,也就是说,两件事同时需要CPU的情况并不是这样。在这种情况下,多线程可能是更好的解决方案,即您应该使用James的解决方案。
如果您仍然想进行多处理,那么下面的代码可能是您对计时器的基本设置。对于语音识别功能,相应地(特别是返回列表的部分应该足以从语音识别中返回tts ):
import multiprocessing
import time
def timer_with_return(seconds, return_list):
time.sleep(seconds)
return_list.append('foo')
if __name__ == "__main__":
# variables by manager are shared among process
# e.g. for return values
manager = multiprocessing.Manager()
timer_return = manager.list()
timer = multiprocessing.Process(target=timer_with_return, args=(3, timer_return))
timer.start()
while True:
time.sleep(1)
if not timer.is_alive():
break
print("timer is still running")
timer.join() # make sure the process is really finished
print("timer finished, return value is {}".format(timer_return))运行此操作将产生:
timer is still running
timer is still running
timer is still running
timer finished, return value is ['foo']https://stackoverflow.com/questions/47966717
复制相似问题