在处理Python2.7中的CSV文件时,我在使用ThreadPool和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秒。
发布于 2017-11-17 18:11:53
这是你的问题
for batch in batchGenerator:
threadPool.map(processBatch, (batch,))当我试着
threadPool.map(processBatch, batchGenerator)
它发挥了预期的作用(但没有正常运行)。for循环使用一个threadPool来处理每个批每次一次.所以它完成了一个,然后继续,然后.
https://stackoverflow.com/questions/47356159
复制相似问题