Python多处理中的子对父通信 [英] Child to parent communication in Python multiprocessing

查看:63
本文介绍了Python多处理中的子对父通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a python script that will parse through a file quickly by sending lines to different processes to handle. At the end, I want the parent to receive the results from each child process and then be able to manipulate that. Here is the code:

#!/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.如何将行数发送给父级?

As you can see, each child can save its line count, but when I try to access the count from the parent, I keep getting 0. How can I send the line count to the parent?

推荐答案

您可以将值传回结果队列.

You can pass values back through an results queue.

在LineConsumer中:

In LineConsumer:

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多处理中的子对父通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆