2012-07-17 67 views
41

我在嘗試瞭解多處理隊列如何在python上工作以及如何實現它時遇到了很多麻煩。假設我有兩個從共享文件訪問數據的python模塊,我們稱這兩個模塊爲編寫器和讀者。我的計劃是讓讀寫器都將請求放入兩個單獨的多處理隊列中,然後讓第三個進程在循環中彈出這些請求並執行。如何在Python中使用多處理隊列?

我的主要問題是,我真的不知道如何正確地實現multiprocessing.queue,你不能真正實例化每個進程的對象,因爲它們將是單獨的隊列,你如何確保所有進程與一個共享隊列(或在這種情況下,隊列)

+3

當您在父進程中實例化它們時,將隊列作爲參數傳遞給每個進程類。 – 2012-07-17 04:20:06

回答

57

我的主要問題是,我真的不知道如何正確地實施multiprocessing.queue,你不能真正實例化對象的每一個過程,因爲他們將是不同的隊列,您如何確保所有進程都與共享隊列相關(或者在這種情況下是隊列)

這是讀寫器共享單個隊列的一個簡單例子......作者向讀者發送一串整數;當作者用完數字時,它會發送'DONE',讓讀者知道跳出讀取循環。

from multiprocessing import Process 
from queue import Queue 
import time 

def reader(queue): 
    ## Read from the queue 
    while True: 
     msg = queue.get()   # Read from the queue and do nothing 
     if (msg == 'DONE'): 
      break 

def writer(count, queue): 
    ## Write to the queue 
    for ii in xrange(0, count): 
     queue.put(ii)    # Write 'count' numbers into the queue 
    queue.put('DONE') 

if __name__=='__main__': 
    for count in [10**4, 10**5, 10**6]: 
     queue = Queue() # reader() reads from queue 
          # writer() writes to queue 
     reader_p = Process(target=reader, args=((queue),)) 
     reader_p.daemon = True 
     reader_p.start()  # Launch reader() as a separate python process 

     _start = time.time() 
     writer(count, queue) # Send a lot of stuff to reader() 
     reader_p.join()   # Wait for the reader to finish 
     print "Sending %s numbers to Queue() took %s seconds" % (count, 
      (time.time() - _start)) 
+6

很好的例子。就像解決OP的混亂問題一樣,還有一點信息......這個例子表明共享隊列需要源自主進程,然後傳遞給它的所有子進程。爲了使兩個完全不相關的進程共享數據,它們必須通過一些中央或相關網絡設備(例如套接字)進行通信。有些事情必須協調這些信息。 – jdi 2012-07-17 05:28:38

+4

很好的例子..我也是新來這個主題..如果我有多個進程運行相同的目標函數(不同的參數),如何確保他們不會衝突,而把數據放入隊列..是鎖必要? – WYSIWYG 2014-01-04 17:26:35

+0

@bharat_iyengar從多處理模塊文檔中可以看出,使用幾個鎖/信號量來實現Queue。所以,當你使用get()和put(對象)隊列方法時,如果其他進程/線程正在嘗試獲取或在隊列中放置某些東西,隊列將會阻塞。所以你不必擔心手動鎖定它。 – almel 2014-06-05 22:01:58

1

在「from queue import Queue」中沒有模塊叫做queue,而應該使用多處理。因此,它應該看起來像「從多處理進口隊列」

+0

https://docs.python.org/3/library/queue.html – Jakub 2018-02-05 13:59:19