擅长:python、mysql、java
<p>一种可能是使用多处理命名空间中的Queue对象。描述如下:
<a href="http://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes" rel="nofollow">http://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes</a></p>
<p>所以我修改了你的代码。我只做了两个改动:
-使用多处理队列
-避免使用全局变量,并将队列作为参数传递给worker和queuer(这不是必需的,但保持所有内容整洁是一个很好的实践)</p>
<pre><code># 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()
</code></pre>