正确使用 ThreadPool 和 Generators

Loi*_*all 4 python yield-keyword multiprocessing threadpool python-multiprocessing

在 Python 2.7 中处理 CSV 文件时,我在使用ThreadPools 和 aGenerator时遇到问题。下面是一些示例代码,说明了我的观点:

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()
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我得到了预期的输出:

已处理批次 0

已处理批次 1

已处理批次 2

已处理批次 3

已处理批次 4

问题是它们在每次打印之间出现1 秒的延迟。实际上,我的脚本是按顺序运行的(而不是像我希望的那样使用多个线程)。

这里的目标是让这些打印的语句在大约 1 秒后全部出现,而不是在 5 秒内每秒出现一个。

e.s*_*.s. 5

这是你的问题

for batch in batchGenerator:
    threadPool.map(processBatch, (batch,))
Run Code Online (Sandbox Code Playgroud)

当我尝试

threadPool.map(processBatch, batchGenerator)

它按预期工作(但不按顺序)。for 循环使用 threadPool 一次处理每个批处理。所以它完成了一个,然后继续前进,然后......