pythonプロセスインタラクション:Queue

9039 ワード

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import datetime
import multiprocessing
from multiprocessing import Process, Manager, Lock, Queue
from threading import Thread
import ctypes, os
import select

class Ethread(Thread):
    def __init__(self, dic, print1):
        super(Ethread, self).__init__()
        self.dict = dic
        self.print1 = print1

    def run(self):
        while True:
            if self.dict:
                self.print1()
                if len(self.dict) >= 10:
                    break

class EPool(Process):
    def __init__(self, queue):
        super(EPool, self).__init__()
        self.dict = {}
        self.queue = queue

    def emit(self, msg):
        self.dict[msg] = msg

    def print1(self):
        print("%s" %self.dict)

    def run(self):
        self.thread = Ethread(self.dict, self.print1)
        self.thread.start()

        while True:
            try:
                msg = self.queue.get()
                self.emit(msg)
            except Exception as e:
                print(e)


class EProcess(Process):
    def __init__(self, queue):
        super(EProcess, self).__init__()
        self.queue = queue

    def run(self):
        for i in range(10):
            self.queue.put(i)

def main():
    queue = multiprocessing.Queue()

    pool = EPool(queue)
    pool.start()

    process = EProcess(queue)
    process.start()

main()


結果:{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9}