为什么我在 Python 的主线程中看不到写入子进程的队列?

Why can't I see the queue written to in a subprocess in my main thread in Python?

我有一个使用多重处理的简单程序。它基本上执行数学运算并将结果写入队列。我可以看到队列大小在多处理函数内部增长,但是一旦我在主 thread/process 之外,队列就空了。这似乎是我不理解的某种范围界定问题。有人可以解释为什么在函数外队列为空吗?我试过将队列作为参数传递给函数,以及其他方法,但它似乎总是空的。

from multiprocessing import Pool, Process
import math
import Queue

q = Queue.Queue(maxsize=0)


def compute_and_write(val):
    sq = val * val
    sq = math.sqrt(sq)
    sq = sq + sq + sq
    q.put("Q" + str(sq))
    print "Queue size (inside) = " + str(q.qsize())
    return sq


p = Pool(8)
y = []

for x in range(1, 100):
    y.append(x)

res = p.map(compute_and_write, y)
print "Queue size (outside) = " + str(q.qsize())

A Queue.Queue 与 cross-process 行为方面的列表或字典没有什么不同:每个进程都有自己不同的对象,并且一个进程的副本中的更改在全部在任何其他进程的副本上。

您需要 multiprocessing.Queue。这旨在让状态在 进程中可见。这就是它应该有的一切。