2017-04-10 64 views
0

撿更多的工作,我非常的品牌新的Python和我一直在努力,它分析在任何給定的目錄中的CSV文件的腳本。我實現了一個隊列和線程後,我一直停留在不拿起新的工作線程的這個問題,儘管仍有隊列中的項目。例如,如果我指定線程的最大#爲3,並有在隊列中6項,線程拿起3個文件,對它們進行處理,然後掛機,無限期。我可能只是在概念上誤解了多線程的過程。線程不是從隊列

ETA: 某些代碼已出於安全原因刪除。

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

你忘了一個循環遍歷你的線程隊列 ...

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

這就是說,你也許重新發明輪子,請嘗試使用線程池

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