python - Python多处理中的子到父通信

标签 python multiprocessing

我正在编写一个 python 脚本,它将通过将行发送到不同的进程来处理来快速解析文件。最后,我希望父进程从每个子进程接收结果,然后能够对其进行操作。这是代码:

#!/usr/bin/env python
import os
import re

from datetime import datetime
from multiprocessing import Process, JoinableQueue

class LineConsumer(Process):

    def __init__(self, queue):
        self.queue = queue
        self.lines = 0
        super(LineConsumer, self).__init__( )

    def run(self):
        print "My PID is %d" % self.pid

        while True:
            line = self.queue.get( )
            print self.lines
            if ':' in line:
                self.lines += 1
            self.queue.task_done( )

class Parser(object):

    def __init__(self, filename, processes=4):
        self.filename = filename
        self.processes = processes

    def parse(self):
        queue = JoinableQueue(100)
        consumers = [ ]
        parents = [ ]
        for i in range(0, self.processes):
            lc = LineConsumer(queue)
            lc.start( )
            consumers.append(lc)

        starttime = datetime.now( )
        problem = False
        numlines = 0

        with open(self.filename, 'r') as data:
            for line in data:
                numlines += 1

                def checkAlive(p):
                    if not p.is_alive( ):
                        return False
                    return True

                alive = map(checkAlive, consumers)
                if False in alive:
                    problem = True
                    print "A process died!!!"
                    break
                queue.put(line)

        if not problem:
            queue.join( )

        for p in consumers:
            print p.lines( )
            p.terminate( )
            p.join( )

        endtime = datetime.now( )
        timedelta = endtime - starttime 
        lps = numlines / timedelta.total_seconds( )
        print "Processed packets at %f lps" % lps

if __name__ == "__main__":
    import sys

    if len(sys.argv) != 2:
        print "Supply a file to read"
        sys.exit(1)

    parser = Parser(sys.argv[1])
    parser.parse( )

结果如下:

My PID is 11578
My PID is 11579
My PID is 11580
My PID is 11581
0
1
0
2
1
3
2
1
...
555
627
564
556
628
0
0
0
0
Processed packets at 27189.771341 lps

如您所见,每个子级都可以保存其行数,但是当我尝试从父级访问计数时,我一直得到 0。如何将行数发送给父级?

最佳答案

您可以通过结果队列传回值。

在线消费者:

def __init__(self, queue, result_queue):
   self.result_queue = result_queue
   # ...

def terminate(self):
   self.results_queue.put(self.lines)
   super(LineConsumer, self).terminate()

在解析器中:

queue = JoinableQueue(100)
result_queue = Queue()
# ...
  lc = LineConsumer(queue, result_queue)
# ...
for p in consumers:
  p.terminate()
  p.join()

while True:
  try:
    print results.queue.get(False)
  except Queue.Empty: # need to import Queue
    break

关于python - Python多处理中的子到父通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8172965/

相关文章:

python - 一个 32 位的 Python 脚本调用在 64 位 virtualenv 中运行的多进程

Python 3 Multiprocessing Pool 对于大变量来说很慢

python - Python 中进程群调度的简单示例?

python - 在 Python 中向下舍入日期时间对象

python - 带有 block 字符的终端中的文本进度条

python - 根据另一个列表列表筛选列表列表

python - 在不同的进程中使用管理器/代理公开对象

python - django 管理器获取任何一个对象

python - 使用python regex计算文档中单词的频率

multithreading - 为什么多线程经常与多处理结合使用?