我有两个进程,一个将作业添加到队列中,另一个将它们从同一个队列中取出并运行它们。这应该按预期工作,我不知道为什么worker
永远不会得到任何工作。这是我的代码:
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 :(得分:6)
两件事:
此代码适用于我:
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 :(得分:1)
一种可能性是使用多处理命名空间中的Queue对象。它在这里描述: http://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes
所以我调整了你的代码。我只做了两次改动: - 使用多处理队列 - 避免使用全局变量并将队列作为参数传递给worker和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()