在Python中,如何在两个进程之间共享变量?
我有两个进程,一个将作业添加到队列,另一个将作业从同一队列中取出并运行它们。这应该会像预期的那样起作用,我不知道为什么在Python中,如何在两个进程之间共享变量?,python,multiprocessing,Python,Multiprocessing,我有两个进程,一个将作业添加到队列,另一个将作业从同一队列中取出并运行它们。这应该会像预期的那样起作用,我不知道为什么工人永远得不到任何工作。这是我的密码: from multiprocessing import Process from Queue import Queue import time q = Queue() def queuer(): while True: q.put("JOB") print "Adding JOB"
工人
永远得不到任何工作。这是我的密码:
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()
两件事:
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()
两件事:
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()
一种可能性是使用多处理命名空间中的队列对象。这里描述的是: 所以我修改了你的代码。我只做了两个改变: -使用多处理队列 -避免使用全局变量,并将队列作为参数传递给工作者和排队者(这不是必需的,但最好保持一切整洁)
一种可能性是使用多处理命名空间中的队列对象。这里描述的是: 所以我修改了你的代码。我只做了两个改变: -使用多处理队列 -避免使用全局变量,并将队列作为参数传递给工作者和排队者(这不是必需的,但最好保持一切整洁)
每个进程都有自己的队列副本。还有另一个stackoverflow线程讨论这个问题:每个进程都有自己的队列副本。另一个stackoverflow线程讨论了这一点: