How do you share a variable between two processes in Python?
Question: I have two processes, one adds jobs to a queue and the other takes them off
the same queue and runs them. This should work as expected and I'm not sure
why the `worker` never gets any jobs. Here's my code:

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


Answer: Two things:

  1. You need to pass the Queue as an argument to both processes.
  2. You should use multiprocessing.Queue, not Queue.Queue (which are for Threads)

This code works for me:

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

