【问题标题】:Bounded Buffer (producer/consumer) with python 3.5python 3.5的有界缓冲区(生产者/消费者)
【发布时间】:2025-11-27 06:35:01
【问题描述】:

我正在 Python 3.5 中编写经典的生产者/消费者问题,使用 deque 作为 buff 和 2 个应该并行工作的进程,但不幸的是只有生产者工作,而消费者不“消费”.. 我在哪里错误的?这是我的代码:

from time import sleep
import random
from collections import deque
import multiprocessing

MAX_LEN = 10
buff = deque(maxlen=MAX_LEN)

class producer:
    while True:
        if len(buff) == MAX_LEN:
            print("Producer: The buff is full, waiting...")
            sleep(10)
        buff.append(random.randint(1,9))


class consumer:
    while True:
        print("Consumer: hi")
        if len(buff) == 0:
            print("Consumer: The buff is empty, waiting...")
            sleep(10)
        buff.pop()



if __name__ == '__main__':
    multiprocessing.Process(target=producer).start().join()
    multiprocessing.Process(target=consumer).start().join()

结果是:

Producer: The buff is full, waiting...
Producer: The buff is full, waiting...
Producer: The buff is full, waiting...
Producer: The buff is full, waiting...
Producer: The buff is full, waiting...
Producer: The buff is full, waiting...
^CTraceback (most recent call last):
  File "./boundedbuffer.py", line 9, in <module>
    class producer:
  File "./boundedbuffer.py", line 13, in producer
    sleep(10)
KeyboardInterrupt

现在我想以这种方式实现,作为一个练习,只是为了看看我是否理解这个论点,虽然我知道这不是最正确的,我应该使用信号量或监视器。也许以后我会尝试以不同的方式实现它。 提前感谢大家的帮助,晚上好:)

【问题讨论】:

    标签: python asynchronous parallel-processing multiprocessing


    【解决方案1】:

    您已在其主体中定义了带有while True: 循环的类。

    解释器将永远执行文件中的第一个 while 循环。

    multiprocessing.Process 需要一个可调用对象作为其目标参数,因此如果您将生产者和消费者类更改为函数,则将执行 if __ name __ == __ main __ : 块(尽管您可能仍然无法获得预期的结果)。

    def producer():
        while True:
            if len(buff) == MAX_LEN:
                print("Producer: The buff is full, waiting...")
                sleep(10)
            buff.append(random.randint(1,9))
    
    
    def consumer():
        while True:
            print("Consumer: hi")
            if len(buff) == 0:
                print("Consumer: The buff is empty, waiting...")
                sleep(10)
            buff.pop()
    

    【讨论】:

    • 不幸的是不起作用..我有同样的问题..怎么了?
    • 您可以通过定义 __ call __ 方法使类成为可调用的。您不能在进程之间共享双端队列 - 请参阅 *.com/questions/27345332/…。另请阅读有关共享状态的多处理文档:docs.python.org/3/library/…