multiprocessing.Queue 奇怪的 python 行为
multiprocessing.Queue weird python behavior
我坚持理解非常简单的案例。
请有人解释或指示理解以下内容的方向:
import multiprocessing as mp
if __name__ == '__main__':
input_queue = mp.Queue()
for i in range(5):
input_queue.put([i]*5)
print(input_queue.qsize())
while not input_queue.empty():
o = input_queue.get()
print(o)
输出:
5
[0, 0, 0, 0, 0]
[1, 1, 1, 1, 1]
[2, 2, 2, 2, 2]
[3, 3, 3, 3, 3]
[4, 4, 4, 4, 4]
但是:
import multiprocessing as mp
if __name__ == '__main__':
input_queue = mp.Queue()
for i in range(5):
input_queue.put([i]*5)
# print(input_queue.qsize())
while not input_queue.empty():
o = input_queue.get()
print(o)
什么都不输出
更新:
import multiprocessing as mp
if __name__ == '__main__':
input_queue = mp.Queue()
for i in range(5):
input_queue.put([i]*5)
for _ in range(5):
o = input_queue.get()
print(o)
打印预期输出。所以可能在 .empty() 方法中出现问题。
python --version
Python 3.6.9 :: Anaconda, Inc.
你可能会打 this
After putting an object on an empty queue there may be an infinitesimal delay before the queue’s empty() method returns False
你能试试在while not input_queue.empty():
之前的线路上加个sleep吗?
import multiprocessing as mp
import time
if __name__ == '__main__':
input_queue = mp.Queue()
for i in range(5):
input_queue.put([i]*5)
# print(input_queue.qsize())
time.sleep(1)
while not input_queue.empty():
o = input_queue.get()
print(o)
如果上述方法有效,那么第一个示例中的 print(input_queue.qsize())
调用就是为队列提供足够时间来腌制对象并开始在 empty() 调用中返回 False
的原因。
我坚持理解非常简单的案例。 请有人解释或指示理解以下内容的方向:
import multiprocessing as mp
if __name__ == '__main__':
input_queue = mp.Queue()
for i in range(5):
input_queue.put([i]*5)
print(input_queue.qsize())
while not input_queue.empty():
o = input_queue.get()
print(o)
输出:
5
[0, 0, 0, 0, 0]
[1, 1, 1, 1, 1]
[2, 2, 2, 2, 2]
[3, 3, 3, 3, 3]
[4, 4, 4, 4, 4]
但是:
import multiprocessing as mp
if __name__ == '__main__':
input_queue = mp.Queue()
for i in range(5):
input_queue.put([i]*5)
# print(input_queue.qsize())
while not input_queue.empty():
o = input_queue.get()
print(o)
什么都不输出
更新:
import multiprocessing as mp
if __name__ == '__main__':
input_queue = mp.Queue()
for i in range(5):
input_queue.put([i]*5)
for _ in range(5):
o = input_queue.get()
print(o)
打印预期输出。所以可能在 .empty() 方法中出现问题。
python --version
Python 3.6.9 :: Anaconda, Inc.
你可能会打 this
After putting an object on an empty queue there may be an infinitesimal delay before the queue’s empty() method returns False
你能试试在while not input_queue.empty():
之前的线路上加个sleep吗?
import multiprocessing as mp
import time
if __name__ == '__main__':
input_queue = mp.Queue()
for i in range(5):
input_queue.put([i]*5)
# print(input_queue.qsize())
time.sleep(1)
while not input_queue.empty():
o = input_queue.get()
print(o)
如果上述方法有效,那么第一个示例中的 print(input_queue.qsize())
调用就是为队列提供足够时间来腌制对象并开始在 empty() 调用中返回 False
的原因。