2016-03-14 46 views
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 

只是現在我想通過這種方式來實現,作爲一個練習,只是爲了看看我理解的說法,雖然我知道這不是最正確的,我應該使用信號量或監視器。也許以後我會嘗試以不同的方式實現它。 非常感謝大家的幫助和美好的傍晚:)

回答

0

您已經在他們的身體中定義了帶有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() 
+0

不幸的是不工作..我有同樣的問題..有什麼不對? – Alucard

+0

您可以通過定義__調用__方法來使類可調用。 您不能在進程之間共享一個雙端隊列 - 請參閱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

+0

好的,我該怎麼辦?我必須使用一個數組? – Alucard

相關問題