【发布时间】: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