如何在Python中共享两个进程的变量?

2 投票
2 回答
5564 浏览
提问于 2025-04-17 22:02

我有两个进程,一个是把任务放到队列里,另一个是从同一个队列里取出任务并执行。这应该是正常工作的,但我不明白为什么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()

2 个回答

1

一种可能的方法是使用来自多进程命名空间的队列对象。这里有相关的说明:http://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes

所以我对你的代码做了一些调整。我只做了两个改动: - 使用多进程队列 - 避免使用全局变量,并将队列作为参数传递给工作者和队列创建者(虽然这不是必须的,但这样做可以让代码更整洁)

# 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()
8

有两件事:

  1. 你需要把队列(Queue)作为参数传递给两个进程。
  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()

撰写回答