【问题标题】:Different O/P for same multiprocessing code相同多处理代码的不同 O/P
【发布时间】:2018-05-13 09:47:45
【问题描述】:

我的代码: 在 repl.it IDE 中运行它

from multiprocessing import Queue

colors = ['red', 'green', 'blue', 'black']
cnt = 1
# instantiating a queue object
queue = Queue()
print('pushing items to queue:')
for color in colors:
    print('item no: ', cnt, ' ', color)
    queue.put(color)
    cnt += 1

print('\npopping items from queue:')
cnt = 1
while not queue.empty():
    print('item no: ', cnt, ' ', queue.get())
    cnt += 1

但是每次我运行它,o/p 每次都不同,这是为什么呢?

1 -

 pushing items to queue:
item no:  1   red
item no:  2   green
item no:  3   blue
item no:  4   black

popping items from queue:
item no:  1   red
item no:  2   green
item no:  3   blue
item no:  4   black

2- 这次它不显示 get o/p

pushing items to queue:
item no:  1   red
item no:  2   green
item no:  3   blue
item no:  4   black

popping items from queue:

3- 这次只有 get() 部分的 2 o/p

pushing items to queue:
item no:  1   red
item no:  2   green
item no:  3   blue
item no:  4   black

popping items from queue:
item no:  1   red
item no:  2   green

为什么会这样!这与我不知道的一些隐藏的多处理有关吗?

提前致谢。

【问题讨论】:

    标签: python-3.x python-multiprocessing


    【解决方案1】:

    multiprocessing.Queue 是通过使用 线程 实现的。这意味着每次一个项目是put 在某些情况下,例如您的脚本,线程需要拾取主线程更快,而不是所有项目正在接机。

    如果您稍加延迟 (time.sleep(0.5 # for example.),您会看到它再次正常运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多