1

파이썬 2.7에서 CSV 파일을 처리 할 때 Generator으로 ThreadPool을 사용하는 데 문제가 있습니다.Generator에서 ThreadPool을 올바르게 사용하십시오.

가공 일괄 0

가공 배치 한

가공 배치 :이 프로그램을 실행할 때

from multiprocessing.dummy import Pool as ThreadPool 
import time 

def getNextBatch(): 
    # Reads lines from a huge CSV and yields them as required. 
    for i in range(5): 
     yield i; 

def processBatch(batch): 
    # This simulates a slow network request that happens. 
    time.sleep(1); 
    print "Processed Batch " + str(batch); 

# We use 4 threads to attempt to aleviate the bottleneck caused by network I/O. 
threadPool = ThreadPool(processes = 4) 

batchGenerator = getNextBatch() 

for batch in batchGenerator: 
    threadPool.map(processBatch, (batch,)) 

threadPool.close() 
threadPool.join() 

, 내가 예상 출력을 얻을 : 여기 내 지점을 보여 일부 샘플 코드는 2

처리 배치 3

가공 일괄 4

문제들은 각각의 인쇄 사이 1초 지연으로 나타나는 것이다. 사실, 스크립트는 순차적으로 실행되고 있습니다 (그리고 여러 스레드를 사용하지는 않습니다).

목표는 5 초 동안 초당 1 초가 아닌 ~ 1 초 후에 나타나는 모든 인쇄 문을 얻는 것입니다.

답변

3

는 여기에 내가 (하지만 순서대로) 예상대로 작동

threadPool.map(processBatch, batchGenerator)

을 시도하여 문제

for batch in batchGenerator: 
    threadPool.map(processBatch, (batch,)) 

입니다. for 루프는 threadPool을 사용하여 각 배치를 한 번에 하나씩 처리합니다. 그래서 그것은 하나를 끝내고, 그 다음으로 계속 전진했습니다. ...