Home  >  Q&A  >  body text

python中为什么类的实例方法不可以直接访问队列全局变量?

我想在类中实例中使用全局变量队列,我创建的队列mybuffer作为全局变量,然后Producer和Consume两个类的实例中使用这个全局变量,实际在windows的cmd中的的执行情况是class Producer中的的queue.put()一直在执行,但是class Consumer中的get()确一直没有得到队列中的元素,感觉这个mybuffer到两个类中变成了局部变量。


如果我把mybuffer队列做为成员变量分别传到两个类的实例中是可以正常的put()和get()

不知道全局变量的队列在类里面却不能用了。。。。。。

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

from multiprocessing import Process, Semaphore, Lock, Queue
import time


mybuffer = Queue(10)

class Consumer(Process):
    def __init__(self,lock):
        Process.__init__(self)
        self.lock = lock
    def run(self):
        global mybuffer
        while True:
            mybuffer.get()
            self.lock.acquire()
            print('Consumer pop an element')
            self.lock.release()
            time.sleep(1)


class Producer(Process):
    def __init__(self,lock):
        Process.__init__(self)
        self.lock = lock
    def run(self):
        global mybuffer
        while True:
            mybuffer.put('1')
            self.lock.acquire()
            print('Producer append an element')
            self.lock.release()
            time.sleep(1)


if __name__ == '__main__':
    #mybuffer = Queue(10)
    lock = Lock()
    p = Producer(lock)
    c = Consumer(lock)
    c.start()
    p.start()
    p.join()
    c.join()
    print 'Ended!'
巴扎黑巴扎黑2741 days ago835

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-18 10:17:02

    The above code is correct when I execute it under macOS.

    Producer append an element
    Consumer pop an element
    Producer append an element
    Consumer pop an element

    Is it because of windows?
    I remember that windows does not support fork, windows simulates fork. What's even weirder is that when window creates a new process, it will import the file that created it (see another answer https://segmentfault.com/q/10... for details). And you create a queue at the beginning of the file. When both Productor and Consumer imported in, they each created a variable called mybuffer?
    That should be the reason.
    Under Windows, I printed the ID (mybuffer) in Customer and Product respectively, and they are different.

    I don’t know what’s right or wrong, I hope it helps.

    reply
    0
  • Cancelreply