为什么这个队列会这样?
Why does this queue behave like this?
我正在编写一个从多处理队列中提取的对象,我发现当我 运行 这段代码时,我得到 data = []
。而如果我告诉程序在指定的地方休眠一会儿,我会得到 data = [1,2]
,因为它应该。
from multiprocessing import Queue
import time
q = Queue()
taken = 0
data = []
for i in [1,2]:
q.put(i)
# time.sleep(1) making this call causes the correct output
while not q.empty() and taken < 2:
try:
data.append(q.get(timeout=1))
taken+=1
except Empty:
continue
**编辑:**如果 while 循环之前有打印语句,也会发生这种情况。这向我表明,正在发生对 q.put() 的调用,但我找不到关于此问题的任何文档。
在 docs 中提到了 multiprocessing.Queue
Note When an object is put on a queue, the object is pickled and a
background thread later flushes the pickled data to an underlying
pipe. This has some consequences which are a little surprising, but
should not cause any practical difficulties – if they really bother
you then you can instead use a queue created with a manager.
- After
putting an object on an empty queue there may be an infinitesimal
delay before the queue’s empty() method returns False and get_nowait()
can return without raising Queue.Empty.
...
我正在编写一个从多处理队列中提取的对象,我发现当我 运行 这段代码时,我得到 data = []
。而如果我告诉程序在指定的地方休眠一会儿,我会得到 data = [1,2]
,因为它应该。
from multiprocessing import Queue
import time
q = Queue()
taken = 0
data = []
for i in [1,2]:
q.put(i)
# time.sleep(1) making this call causes the correct output
while not q.empty() and taken < 2:
try:
data.append(q.get(timeout=1))
taken+=1
except Empty:
continue
**编辑:**如果 while 循环之前有打印语句,也会发生这种情况。这向我表明,正在发生对 q.put() 的调用,但我找不到关于此问题的任何文档。
在 docs 中提到了 multiprocessing.Queue
Note When an object is put on a queue, the object is pickled and a background thread later flushes the pickled data to an underlying pipe. This has some consequences which are a little surprising, but should not cause any practical difficulties – if they really bother you then you can instead use a queue created with a manager.
- After putting an object on an empty queue there may be an infinitesimal delay before the queue’s empty() method returns False and get_nowait() can return without raising Queue.Empty. ...