11

我对python相当陌生。我正在使用多处理模块读取标准输入上的文本行,以某种方式转换它们并将它们写入数据库。这是我的代码片段:

batch = []
pool = multiprocessing.Pool(20)
i = 0
for i, content in enumerate(sys.stdin):
    batch.append(content)
    if len(batch) >= 10000:
        pool.apply_async(insert, args=(batch,i+1))
        batch = []
pool.apply_async(insert, args=(batch,i))
pool.close()
pool.join()

现在一切正常,直到我开始处理巨大的输入文件(数亿行),然后通过管道传输到我的 python 程序中。在某些时候,当我的数据库变慢时,我看到内存已满。

玩了一会儿,发现 pool.apply_async 和 pool.map_async 从来没有阻塞过,所以要处理的调用队列越来越大。

解决我的问题的正确方法是什么?我希望我可以设置一个参数,一旦达到某个队列长度,它将阻止 pool.apply_async 调用。Java 中的 AFAIR 可以为此目的给 ThreadPoolExecutor 一个具有固定长度的 BlockingQueue。

谢谢!

4

4 回答 4

13

和函数旨在不阻塞主进程apply_asyncmap_async为了做到这一点,不幸的是,它Pool维护了一个内部Queue大小是不可能改变的。

解决问题的方法是使用Semaphore您希望队列的大小进行初始化。在给池喂食之前和工作人员完成任务之后,您获取并释放信号量。

这是一个使用 Python 2.6 或更高版本的示例。

from threading import Semaphore
from multiprocessing import Pool

def task_wrapper(f):
    """Python2 does not allow a callback for method raising exceptions,
    this wrapper ensures the code run into the worker will be exception free.

    """
    try:
        return f()
    except:
        return None

class TaskManager(object):
    def __init__(self, processes, queue_size):
        self.pool = Pool(processes=processes)
        self.workers = Semaphore(processes + queue_size)

    def new_task(self, f):
        """Start a new task, blocks if queue is full."""
        self.workers.acquire()
        self.pool.apply_async(task_wrapper, args=(f, ), callback=self.task_done))

    def task_done(self):
        """Called once task is done, releases the queue is blocked."""
        self.workers.release()

另一个使用池实现的示例。concurrent.futures

于 2013-09-09T13:47:37.120 回答
11

以防万一有人在这里结束,这就是我解决问题的方法:我停止使用 multiprocessing.Pool。这是我现在的做法:

#set amount of concurrent processes that insert db data
processes = multiprocessing.cpu_count() * 2

#setup batch queue
queue = multiprocessing.Queue(processes * 2)

#start processes
for _ in range(processes): multiprocessing.Process(target=insert, args=(queue,)).start() 

#fill queue with batches    
batch=[]
for i, content in enumerate(sys.stdin):
    batch.append(content)
    if len(batch) >= 10000:
        queue.put((batch,i+1))
        batch = []
if batch:
    queue.put((batch,i+1))

#stop processes using poison-pill
for _ in range(processes): queue.put((None,None))

print "all done."

在 insert 方法中,每个批次的处理都包装在一个循环中,该循环从队列中拉出,直到它收到毒丸:

while True:
    batch, end = queue.get()
    if not batch and not end: return #poison pill! complete!
    [process the batch]
print 'worker done.'
于 2012-03-08T15:11:07.580 回答
2

apply_async返回一个AsyncResult对象,你可以wait

if len(batch) >= 10000:
    r = pool.apply_async(insert, args=(batch, i+1))
    r.wait()
    batch = []

但是,如果您想以更简洁的方式执行此操作,则应使用 amultiprocessing.Queuemaxsize10000,并从从此类队列中获取的类派生一个Worker类。multiprocessing.Process

于 2012-03-07T13:07:12.087 回答
1

不漂亮,但您可以访问内部队列大小并等到它低于您的最大期望大小,然后再添加新项目:

max_pool_queue_size = 20

for i in range(10000):
  pool.apply_async(some_func, args=(...))

  while pool._taskqueue.qsize() > max_pool_queue_size:
    time.sleep(1)
于 2018-09-22T03:59:38.357 回答