【发布时间】:2018-05-01 13:20:19
【问题描述】:
在 Python 2.7 中处理 CSV 文件时,我在使用 ThreadPools 和 Generator 时遇到问题。下面是一些示例代码来说明我的观点:
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()
当我运行它时,我得到了预期的输出:
已处理批次 0
已处理的批次 1
已处理的批次 2
已处理的批次 3
已处理的批次 4
问题在于它们在每次打印之间出现 1 秒延迟。实际上,我的脚本是按顺序运行的(而不是像我希望的那样使用多个线程)。
这里的目标是让那些打印出来的语句在大约 1 秒后全部出现,而不是每秒一个,持续 5 秒。
【问题讨论】:
标签: python multiprocessing threadpool python-multiprocessing yield-keyword