在执行 Python 程序时,我做错了什么,因为我的全局队列为空?

What am I doing wrong, in following Python program, as I'm getting global queue empty?

我已经编写了这个获取列表输入的小虚拟程序,例如

[1, 2, 3, 4]

那么输出应该是

{1:2, 2:4, 3:6, 4:8}

当我打印输出时

{1: 2}
{2: 4}
{3: 6}
{4: 8}
True
True
True
True
{}

但是队列是空的。

import Queue
import math
import multiprocessing   

out_q = Queue.Queue()

def mp_factorizer(nums):
    global out_q
    def worker(num):
        outdict = {}
        outdict[num] = num * 2
        print outdict
        out_q.put(outdict)

    procs = []
    for num in nums:
        p = multiprocessing.Process(target=worker,args=(num,))
        procs.append(p)
        p.start()

    resultdict = {}

    for p in procs:
        p.join()

    for i in range(len(nums)):
        print out_q.empty()
        if not out_q.empty():
            resultdict.update(out_q.get())

    # Wait for all worker processes to finish

    return resultdict

di = mp_factorizer([1, 2, 3, 4])
print di

不要为队列对象使用全局变量。它不在进程之间共享。请改用 multiprocessing.Queue 并将其作为参数传入,以便对其进行管理:

def mp_factorizer(nums):
    out_q = multiprocessing.Queue()

    def worker(num, out_q):
        outdict = {}
        outdict[num] = num * 2
        print outdict
        out_q.put(outdict)


    procs = []

    for num in nums:
        p = multiprocessing.Process(
                target=worker,
                args=(num, out_q)
        )
        procs.append(p)
        p.start()

    for p in procs:
        p.join()

    resultdict = {}
    for i in range(len(nums)):
        if not out_q.empty():
            resultdict.update(out_q.get())

    return resultdict