2014-03-12 72 views
0

我有兩個進程,一個將作業添加到隊列中,另一個將它們從同一隊列中取出並運行它們。這應該按預期工作,我不知道爲什麼worker從未得到任何工作。這裏是我的代碼:如何在Python中的兩個進程之間共享一個變量?

from multiprocessing import Process 
from Queue import Queue 
import time 

q = Queue() 

def queuer(): 
    while True: 
     q.put("JOB") 
     print "Adding JOB" 
     time.sleep(1) 

def worker(): 
    while True: 
     if not q.empty(): 
      item = q.get() 
      print "Running", item 
     else: 
      print "No jobs" 
      time.sleep(1) 

a = Process(target=queuer) 
a.start() 

b = Process(target=worker) 
b.start() 
+0

每個進程都有它自己的隊列副本。有另一個stackoverflow線程討論這個:http://stackoverflow.com/questions/11109776/changing-global-variable-when-multiprocessing-in-python – wizard23

回答

5

兩件事情:

  1. 您需要通過隊列作爲參數傳遞給這兩個進程。
  2. 你應該使用multiprocessing.Queue,不Queue.Queue(這是線程)

此代碼的工作對我來說:

from multiprocessing import Process, Queue 
import time 

def queuer(q): 
    while True: 
     q.put("JOB") 
     print "Adding JOB" 
     time.sleep(1) 

def worker(q): 
    while True: 
     if not q.empty(): 
      item = q.get() 
      print "Running", item 
     else: 
      print "No jobs" 
      time.sleep(1) 



if __name__ == '__main__': 
    q = Queue() 
    a = Process(target=queuer, args=(q,)) 
    b = Process(target=worker, args=(q,)) 
    a.start() 
    b.start() 
1

一種可能性是使用隊列對象從多命名空間。這裏描述: http://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes

所以我改編了你的代碼。我只發2點的變化: - 使用多隊列 - 避免全局和傳遞隊列作爲參數傳遞給工人和queuer(這不是必要的,但它是很好的做法,把一切都整潔)

# use the Queue from the multiprocessing namespace! 
from multiprocessing import Process, Queue 
import time 

q = Queue() 

def queuer(q): 
    while True: 
     q.put("JOB") 
     print "Adding JOB" 
     time.sleep(1) 

def worker(q): 
    while True: 
     if not q.empty(): 
      item = q.get() 
      print "Running", item 
     else: 
      print "No jobs" 
      time.sleep(1) 

a = Process(target=queuer, args =(q,)) 
a.start() 

b = Process(target=worker, args = (q,)) 
b.start() 
相關問題