2017-12-25 19 views
0

私はPythonを使って仮想アシスタントを作っています。 私は、音声認識に必要とされ、バックグラウンドで実行するためにスピーチを検出した後、アクションのような他のスレッドを実行したい、連続的に実行する1つのメインスレッドが必要です。Python:メインスレッドを継続的に実行中、バックグラウンドで実行中

タイマーのようなタスクでは、メインスレッドが実行されている間にバックグラウンドで実行したいので、タイマーが実行中であっても他のタスクを実行できます。 >class Main() - - >Running logger in background // which is meant to exit with mainLoop - >and Command() loop for speech recognition continuously - 私が使用しているようtts

メインスレッドへの現在の構造は

main.py あるtimer.pyするBrain.pyにリンク> `

+0

を質問である何? –

+0

マルチスレッドとマルチプロセッシングの違いを説明するために私の答えを改訂しました。これがあなたの質問に答えるかどうかを教えてください – hansaplast

答えて

0

multiprocessingmultithreadingについていくつかの単語:

をマルチスレッドあなたは、現在のプロセス内のスレッドを開始します。 Pythonは短い順番で(global interpreter lockを介して)スレッドを実行しますが、は実際にはと並行しません。スレッドが同じ変数(すなわち共有メモリ)にアクセスできることは有益である。

反対側のマルチプロセスでは、新しいプロセスを実行します(OSでは別のプログラムとして表示されます)。それらは実際には並行して実行できますが、変数を共有するのはずっと難しくなります(さらに遅くなります)。

あなたのユースケースでは、2つの事柄が同時にCPUを100%必要とするケースはありません。この状況では、マルチスレッドがおそらくより良い解決策です。つまり、James Limのソリューションに行くべきです。

まだマルチプロセッシングを使用したい場合は、次のコードをタイマーの基本設定にすることができます。音声認識機能のために、それは(リストを返す程度espeically部分は、音声認識から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'] 
+0

またthnkあなたは非常に助けました – adity

0

threadingはあなたのために機能しますか?

import threading 

# define a thread class for each background component 
class Timer(threading.Thread): 

    def run(self): 
     # ... do timer stuff 

# define other threads 
threads = [...] # instantiate each one 

for t in thread: 
    t.start() 

doMainThread() 
# think really hard about how you wish to handle failures in background threads 

for t in thread: 
    timer.join() 
+0

ansのためにありがとうございます – adity

関連する問題