为什么Semaphore的值不会改变全局

时间:2017-09-19 12:57:57

标签: python multithreading multiprocessing

这是我目前的代码,主要问题是我使用Semphore来控制两个进程的输出,但似乎Semphore并没有改变全局,即当进程“生产者”将Semphore改为2进程时“消费者” “仍然认为Semphore是零,导致它永远等待。

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

buffer = Queue(10)
empty = Semaphore(2)
full = Semaphore(0)

class Consumer(Process):

    def run(self):
        global buffer, empty, full
        while True:
            time.sleep(4)
            print(full)
            full.acquire()
            buffer.get()
            print('Consumer get')
            time.sleep(1)
            empty.release()


class Producer(Process):

    def run(self):
        global buffer, empty, full
        while True:
            empty.acquire()
            print ('Producer put ')
            time.sleep(1)
            full.release()
            buffer.put(1)
            print(full)


if __name__ == '__main__':
    p = Producer()
    c = Consumer()
    p.daemon = c.daemon = True
    p.start()
    c.start()
    p.join()
    c.join()
    print ('Ended!')

,输出

Producer put
<Semaphore(value=1)>
Producer put
<Semaphore(value=2)>
<Semaphore(value=0)>

我不知道如何让“消费者”过程检测到这种变化。

1 个答案:

答案 0 :(得分:0)

您的两个进程都有自己的信号量副本,因为每个进程在实例化时都会在脚本中运行整个代码。

您必须在if __name__ == '__main__':内移动信号量和队列定义,并将信号量的实例传递给ProducerConsumer构造函数,以便它们 使用三个对象的相同实例。

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

class Consumer(Process):
    def __init__(self, empty, full, buffer):
      super(Consumer, self).__init__()
      self.empty = empty
      self.full = full
      self.buffer = buffer

    def run(self):
        while True:
            time.sleep(4)
            print("Consumer: {}".format(self.full), flush=True)
            print("Consumer: buf {}".format(self.buffer.qsize()), flush=True)
            self.full.acquire()
            self.buffer.get()
            print('Consumer get', flush=True)
            time.sleep(1)
            self.empty.release()


class Producer(Process):
    def __init__(self, empty, full, buffer):
      super(Process, self).__init__()
      self.empty = empty
      self.full = full
      self.buffer = buffer

    def run(self):
        while True:
            self.empty.acquire()
            print ('Producer put ', flush=True)
            self.buffer.put('a') #<<<<<<<<<<< you forgot this in your code. If the queue is empty, get() will block on the consumer
            time.sleep(1)
            self.full.release()
            print(self.full, flush=True)


if __name__ == '__main__':
    buffer = Queue(10)
    empty = Semaphore(2)
    full = Semaphore(0)

    p = Producer(empty, full, buffer)
    c = Consumer(empty, full, buffer)
    p.daemon = c.daemon = True
    p.start()
    c.start()
    p.join()
    c.join()
    print ('Ended!')