0
我在Python 3.5中使用deque作爲buff和2進程來編寫經典的生產者/消費者問題,並行工作,但不幸的是只有生產者工作,而消費者不't「消耗」..我錯在哪裏?這是我的代碼:使用Python 3.5綁定緩衝區(生產者/消費者)
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
只是現在我想通過這種方式來實現,作爲一個練習,只是爲了看看我理解的說法,雖然我知道這不是最正確的,我應該使用信號量或監視器。也許以後我會嘗試以不同的方式實現它。 非常感謝大家的幫助和美好的傍晚:)
不幸的是不工作..我有同樣的問題..有什麼不對? – Alucard
您可以通過定義__調用__方法來使類可調用。 您不能在進程之間共享一個雙端隊列 - 請參閱http://stackoverflow.com/questions/27345332/process-vs-thread-with-regards-to-using-queue-deque-and-class-variable-for 。另請閱讀有關共享狀態的多處理文檔:https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes。 – snakecharmerb
好的,我該怎麼辦?我必須使用一個數組? – Alucard