【问题标题】:Correctly use ThreadPool with Generators正确使用 ThreadPool 和 Generators
【发布时间】: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


    【解决方案1】:

    这是你的问题

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

    当我尝试时

    threadPool.map(processBatch, batchGenerator)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-09
      • 2011-02-22
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多