Python多处理apply_async + Value

时间:2012-12-27 13:01:31

标签: python multiprocessing counter shared

我尝试通过apply_async将共享计数器传递给多处理中的任务,但它失败并出现此类错误“RuntimeError:只应通过继承在进程之间共享同步对象”。发生了什么

def processLine(lines, counter, mutex):
    pass

counter = multiprocessing.Value('i', 0)
mutex = multiprocessing.Lock()
pool = Pool(processes = 8)
lines = []

for line in inputStream:
    lines.append(line)
    if len(lines) >= 5000:
         #don't queue more than 1'000'000 lines
         while counter.value > 1000000:
                 time.sleep(0.05)
         mutex.acquire()
         counter.value += len(lines)
         mutex.release()
         pool.apply_async(processLine, args=(lines, counter, ), callback = collectResults)
         lines = []

2 个答案:

答案 0 :(得分:2)

让池处理调度:

for result in pool.imap(process_single_line, input_stream):
    pass

如果订单无关紧要:

for result in pool.imap_unordered(process_single_line, input_stream):
    pass

pool.*map*()函数有chunksize个参数,您可以更改它以查看它是否会影响您的工作效果。

如果您的代码需要在一次调用中传递多行:

from itertools import izip_longest

chunks = izip_longest(*[iter(inputStream)]*5000, fillvalue='') # grouper recipe
for result in pool.imap(process_lines, chunks):
    pass

限制排队项目数量的一些替代方案是:

    设置最大大小的
  • multiprocessing.Queue(在这种情况下您不需要池)。 queue.put()会在达到最大值时阻止,直到其他进程调用queue.get()
  • 使用多处理原语(如Condition或BoundedSemaphor)手动实现生产者/消费者模式。

注意:每个Value都有关联的锁,你不需要单独的锁。

答案 1 :(得分:0)

我用这种不优雅的方式解决了它

def processLine(lines):
    pass

def collectResults(result):
    global counter
    counter -= len(result)

counter = 0
pool = Pool(processes = 8)
lines = []

for line in inputStream:
    lines.append(line)
    if len(lines) >= 5000:
         #don't queue more than 1'000'000 lines
         while counter.value > 1000000:
             time.sleep(0.05)
         counter.value += len(lines)
         pool.apply_async(processLine, args=(lines), callback = collectResults)
         lines = []