如何在python 3.5

时间:2016-03-21 09:35:43

标签: python multithreading python-3.x semaphore producer-consumer

我有同步问题在python 3.5中用信号量创建生产者/消费者问题。特别是当我获得生产者信号量的同时(我认为这是问题,但我不确定,如果是这样,我不知道为什么)消费者信号量获得了,这意味着它是生产者的一个块(在打印中),因为它无法进入“如果buff已满”声明。 这是我的代码:

import random
from queue import Queue
import threading


class producer (threading.Thread):
    def __init__(self, buff, semaphore):
        threading.Thread.__init__(self)
        self.bf = buff
        self.semaphore = semaphore

    def run(self):
        while True:
            self.semaphore.acquire()
            if self.bf.full():
                self.semaphore.release()
                print("Producer: The buff is full, waiting...")
            else:
                x = random.randint(1,9)
                print("Producer: I produced the object # ", x)
                self.bf.put(x)


class consumer (threading.Thread):
    def __init__(self, buff, semaphore):
        threading.Thread.__init__(self)
        self.bf = buff
        self.semaphore = semaphore

    def run(self):
        while True:
            self.semaphore.acquire()
            if self.bf.empty():
                self.semaphore.release()
                print("Consumer: The buff is empty, waiting...")
            else:
                print("Consumer: I consumed the object # ", self.bf.get())


class main:
    MAX_LEN = 10
    semaphore = threading.BoundedSemaphore(value=MAX_LEN)
    buff = Queue(maxsize=MAX_LEN)
    producer = producer(buff, semaphore)
    producer.start()
    consumer = consumer(buff, semaphore)
    consumer.start()


if __name__ == '__main__':
    main

结果是:

Producer: I produced the object #  9
Producer: I produced the object #  3
Producer: I produced the object #  2
Producer: I produced the object #  1
Producer: I produced the object #  4
Producer: I produced the object #  5
Producer: I produced the object #  2
Producer: I produced the object #  1
Producer: I produced the object #  4
Producer: I produced the object #  1

我可以做些什么来解决这个可怕的问题?

0 个答案:

没有答案