2017-04-10 8 views
0

私はPythonにはまったく新しいものです。私は任意のディレクトリ内のcsvファイルを解析するスクリプトに取り組んでいます。私はキューとスレッドを実装した後も、キューに項目が残っていても、新しい作業を取り上げないスレッドのこの問題に取り組んできました。たとえば、スレッドの最大数を3と指定し、キューに6つの項目がある場合、スレッドは3つのファイルを選択して処理し、無期限にハングします。私は概念的にはマルチスレッドプロセスを誤解しているかもしれません。スレッドがキューから多くの作業を拾いません

ETA: セキュリティ上の理由から、コードの一部が削除されています。あなたは多分、車輪を再発明している、と述べたあなたが...あなたのスレッドでキューをループに

def process(): 
    while True: #<---------------- keep getting stuff from the queue 
     with open(q.get()) as csvfile: 
     #do stuff 
      q.task_done() 

を忘れてしまった

q = Queue.Queue() 
threads = [] 

for file in os.listdir(os.chdir(arguments.path)): 
      if (file.endswith('.csv')): 
       q.put(file) 
     for i in range(max_threads): 
      worker = threading.Thread(target=process, name='worker-{}'.format(thread_count)) 
      worker.setDaemon(True) 
      worker.start() 
      threads.append(worker) 
      thread_count += 1 
     q.join() 

def process(): 
     with open(q.get()) as csvfile: 
      #do stuff 
      q.task_done() 

答えて

1

スレッドプールを使用してみてください:

from concurrent.futures import ThreadPoolExecutor 

l = [] # a list should do it ... 
for file in os.listdir(arguments.path): 
     if (file.endswith('.csv')): 
      l.append(file) 

def process(file): 

    return "this is the file i got %s" % file 

with ThreadPoolExecutor(max_workers=4) as e: 
    results = list(e.map(process, l)) 
+0

Derp。有難うございます。 – The31StReaper

関連する問題