2016-06-07 32 views
2

我正在嘗試使用隊列將數據發送到多處理進程。出於某種原因,該示例不起作用。你知道爲什麼嗎?爲什麼進程沒有收到隊列事件?

我希望程序打印出「收到的東西:你好」和「收到毒丸」,但它永遠不會到達那裏。但是,它確實打印出「正在運行」和「正在收聽」,所以我知道它肯定會嘗試從隊列中讀取某些內容。

我使用Pythong 3.4

from multiprocessing import Process 
import queue 
import time 

class EventAggregatorProcess(Process): 

    def __init__(self): 
     super(EventAggregatorProcess, self).__init__() 
     self.event_queue = queue.Queue() 

    def run(self): 
     print('running') 
     is_stopped=False 

     while not is_stopped: 
      print('listening') 
      msg = self.event_queue.get() 
      if msg: 
       print('Received something: %s'%msg) 
      else: 
       print('Received poison pill') 
       is_stopped=True 


if __name__=='__main__': 
    eap = EventAggregatorProcess() 
    eap.start() 
    time.sleep(1) 
    eap.event_queue.put('hello') 
    eap.event_queue.put(None) 

回答

2

queue模塊是用於多線程程序。這些線程都將在一個進程中,這意味着它們也共享內存。 (請參閱docs末尾的另請參閱部分)您的程序是multiprocessing,這意味着您有多個進程。這些進程不共享內存。您應該使用multiprocessing庫中的QueueQueue這個版本處理進程間通信所需的額外工作。

from multiprocessing import Process, Queue 
相關問題