2017-07-11 2 views
1

多くの外部コマンドを実行する必要があるスクリプトを実行しています。そして、私は並行して実行する必要があるコマンドのいくつかのブロックを持っています。Pythonスレッドリストの実行終了後にセマフォーやチェックを作成する

したがって、このスレッドプールが次のスレッドの開始を完了したことを制御する必要があります。

実行されるコマンド:

import pathlib 
def thread_command(path_files, command): 
    _path_files= pathlib.Path(path_files) 
    if pathlib.Path(path_files).exists(): 
    for file in _path_files.glob('**/*.ext'): 

     ext_file = Ext(file, path_files, tmp_rules) 
     if threads == None: 
      threads.insert(0, threading.Thread(target=command)) 
     else: 
      threads.append(threading.Thread(target=command)) 
    return threads 

#Threads running 
command1 = ext_file.command1 
command2= ext_file.command2 
threads1 = thread_command(pathToFiles, command1) 
for thread in threads: 
    thread.daemon = True 
    thread.start() 
do_other_things() 
threads2 = thread_command(pathToFiles, command2) 
for thread in threads2: 
    thread.daemon = True 
    thread.start() 

私がスレッドの最初のリストは、プログラムの実行を継続するために終了したときに制御する方法や手順を見つける必要があります。 要約すると、リストスレッド全体を実行し、そこで実行されるすべてのスレッドが終了するのを待ってから、2番目のスレッドプールを開始します。

ありがとうございました。

+0

join()を使うだけの理由はありますか? joinはスレッドが終了するまで待機します。スレッドのリストを反復してjoin()を呼び出しますか? – Jacobr365

+0

'threads == Noneの場合:threads.insert(...)'は 'threads'がNoneの場合、' insert'メソッドを持たない場合にエラーを発生させます... – GPhilo

+2

なぜスレッドが関与するのでしょうか?サブプロセスで外部コマンドを実行している場合は、[wait](https://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait)を呼び出す前にバンチをオフにするだけです。 –

答えて

1

例えば、彼らが戻ってメインスレッドに参加する代わりに待って、「デーモン」スレッドを使用しないでください。

commands = [ext_file.command1, ext_file.command2] # etc. 
for command in commands: # loop through commands in succession 
    # get the thread list and start it immediately 
    threads_list = [t for t in thread_command(pathToFiles, command) if t.start() is None] 
    for t in threads_list: # loop through all started threads and... 
     t.join() # ... wait for them to join back 

しかし、あなたのthread_command()機能が独自にほとんど意味がない - 初心者のために、あなたは」 threadsリストが定義されていない(少なくとも関数のコンテキスト内にはない)ので、そのリストを挿入/追加しようとするとエラーになります。第二に、ファイルリストが変更されることを期待している場合を除いて、ファイルリストを何度も何度も繰り返し実行しますか?

+0

はい、ファイルリストが変更されることを期待しています。しかし、私は手動で全プロセスをやっていたときと同じように考えていました。あなたが正しい。私はコードのロジックを改造します。 – TMikonos

関連する問題