为什么这个队列会这样?

2024-06-10 04:56:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个从多处理队列中提取的对象,我发现当我运行这段代码时,我得到了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

**EDIT:**while循环之前有print语句时也会发生这种情况。这表明对q.put()的调用发生了一些问题,但我找不到任何关于这个问题的文档。你知道吗


Tags: 对象代码fromimport程序datatime队列
1条回答
网友
1楼 · 发布于 2024-06-10 04:56:35

docs中提到了多处理队列你知道吗

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.

  1. 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. ...

相关问题 更多 >