0

The following code is about the communication between two child processes by queue. I can not figure it out that why the self.q.qsize() is zero and self.q.get() is blocked in the Function "ACT"???.... Since the counter shows the queue is full...

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

from multiprocessing import Process
import multiprocessing
import time
from Queue import Queue

class Test():
    def __init__(self):
        self.q = Queue(1)

    def ACT(self):
        while True:
            print "B momoent queue size: %s" %self.q.qsize()
            print self.q.get()
            time.sleep(1)

    def counter(self):
        for i in range(5,10):
            if not i == 5:
                print "Hello1"
            print self.q.full()
            self.q.join()
            print "Hello2"
            self.q.put(str(i))
            print "A moment queue size: %s" % self.q.qsize()         
if __name__ == '__main__':

    foo = Test()
    qw = Process(target=foo.counter)   
    qw.start()

    qr = Process(target=foo.ACT)
    qr.start()

    qw.join()
    print "End"
forAllBright
  • 61
  • 1
  • 8

1 Answers1

0

You need to use multiprocessing.Queue.

Queue.Queue is meant for threading use. Right now you are creating and using separate queue instances in each process - there is no logic to facilitate the inter-process communication that multiprocessing.Queue provides.

multiprocessing.Queue mirrors most of Queue.Queue methods but you will have to remove join method call and possibly qsize if on OS X.

Jared
  • 25,627
  • 7
  • 56
  • 61
  • But the self.q = Queue(1) is declared in the init part of the Class, and you mean when I call the second Process for "pr" this self.q is fork but not sharing the same memory??? If the truth is not like this, Please give me more help on this conception... – forAllBright May 18 '16 at 15:27
  • @PuMing.Z Correct, while it may share the same memory on certain OSes initially via copy-on-write, changing one will not change the other. – Jared May 18 '16 at 15:28
  • You mean the deepcopy? I appreciate for your help on this. I am keeping going coding now...ha – forAllBright May 18 '16 at 15:29