2017-05-22 29 views
0

私は、テキストファイルを入力として受け取り、テストを実行するスクリプトを持っています。私がしたいのは、2つのスレッドを作成し、入力テキストファイルを2つの部分に分割し、実行時間を最小限に抑えるようにそれらを実行することです。私はこれを行う方法がありますか?Pythonでのスレッディングへの正しいアプローチ

おかげ

class myThread (threading.Thread): 
    def __init__(self, ip_list): 
     threading.Thread.__init__(self) 
     self.input_list = ip_list 

    def run(self): 
     # Get lock to synchronize threads 
     threadLock.acquire() 
     print "python Audit.py " + (",".join(x for x in self.input_list)) 
     p = subprocess.Popen("python Audit.py " + (",".join(x for x in self.input_list)), shell=True) 
     # Free lock to release next thread 
     threadLock.release() 
     while p.poll() is None: 
      print('Test Execution in Progress ....') 
      time.sleep(60) 

     print('Not sleeping any longer. Exited with returncode %d' % p.returncode) 


def split_list(input_list, split_count): 
    for i in range(0, len(input_list), split_count): 
     yield input_list[i:i + split_count] 

if __name__ == '__main__': 

    threadLock = threading.Lock() 
    threads = [] 

    with open("inputList.txt", "r") as Ptr:  
    for i in Ptr: 
     try: 
      id = str(i).rstrip('\n').rstrip('\r') 
      input_list.append(id) 
     except Exception as err: 
      print err 
      print "Exception occured..." 
    try: 
     test = split_list(input_list, len(input_list)/THREAD_COUNT) 
     list_of_lists = list(test) 
    except Exception as err: 
     print err 
     print "Exception caught in splitting list" 

    try: 
     #Create Threads & Start 
     for i in range(0,len(list_of_lists)-1): 
     # Create new threads 
     threads.append(myThread(list_of_lists[i])) 
     threads[i].start() 
     time.sleep(1) 

     # Wait for all threads to complete 
     for thread in threads: 
      thread.join() 
     print "Exiting Main Thread..!" 
    except Exception as err: 
     print err 
     print "Exception caught during THREADING..." 
+0

ロック、 '監査の目的が何であるか:あなたは本当に、並列に2つの操作を行いたい場合に使用すべきである何

はこれを読んでマルチプロセッシングモジュール(輸入マルチプロセッシング)

を使用することです。 py'はいくつかの共通リソースを使用していますか? – ewcz

答えて

1

のバランスを取るために助けることができます同じ時間、これは並列性の定義です。ここで問題となるのは、CPythonを使用している場合、GIL(Global Interpreter Lock)のために並列処理を実行できないということです。 GILは、Pythonインタプリタがスレッドセーフであるとは考えられないため、スレッドが1つしか実行されていないことを確認します。 Multiprocessing vs Threading Python

1

いくつかの注意は、ランダムな順序で:Pythonで

、マルチスレッドは、計算集約的なタスクにアプローチするための良い解決策ではありません。共有されていないリソースについて Python: what are the differences between the threading and multiprocessing modules?

あなたはロックを必要としない(あなたのケースでは、各行は単一のプロセスによって排他的に使用されます):より良いアプローチは、マルチプロセッシングです。より良いアプローチはマップ関数です。

def processing_function(line): 
    suprocess.call(["python", "Audit.py", line]) 

with open('file.txt', 'r') as f: 
    lines = f.readlines() 

to_process = [lines[:len(lines)//2], lines[len(lines)//2:]]  
p = multiprocessing.Pool(2) 
results = p.map(processing_func, to_process) 

計算ではなく、マッピングのプロセス間でデータを移動するためにキューを使用して、行に応じて、時間の可変量を必要とする場合は、あなたがで2つのことをやろうとしている負荷

+0

ありがとう、私は2つのスレッドを実行するために2つの異なるデバイスを使用しています。私はサブプロセスを並列に呼び出すことはできますか? –

+0

2つの異なるデバイスですか?つまり、2つの異なるコンピューティングノードを意味しますか?その場合は、何らかの通信インフラストラクチャが必要になります。このために、MPI4pyまたはipyparallelパッケージをチェックしたいかもしれません。 – user1620443

関連する問題