简体   繁体   English

Python的collection.deque似乎在multiprocessing.Pool中不是线程安全的

[英]Python's collection.deque does not seem to be thread-safe with multiprocessing.Pool

I am working in a small piece of code that is intended to work as follows: 我正在编写一小段代码,其目的如下:

  • An arbitrary number of processes (eg 10) is to be run. 要运行任意数量的进程(例如10个)。
  • Because I have two threads, I want to run them two at a time. 因为我有两个线程,所以我想一次运行两个线程。
  • I want them to read a value from a queue. 我希望他们从队列中读取一个值。 The queue only contains two different values, and I want the two processes running at the same time to read these different values. 队列仅包含两个不同的值,我希望同时运行的两个进程读取这些不同的值。

For instance, consider the next sample code: 例如,考虑下一个示例代码:

import collections
import time

q = collections.deque()
q.append(0)
q.append(1)

def f(i):
    d = q.popleft()
    print d
    time.sleep(1)
    q.append(d)

from multiprocessing import Pool
t = Pool(2)
t.map(f, range(10))

When running this, I expect the first pair of processes to read 0 and 1 respectively. 运行此程序时,我希望第一对进程分别读取0和1。 I don't really mind the order in which they are printed (either 0, 1 or 1, 0). 我真的不介意它们的打印顺序(0、1或1、0)。 However, the output is as follows: 但是,输出如下:

0
0
1
1
0
0
1
1
0
1

Why is this happening if deque is thread-safe? 如果双端队列是线程安全的,为什么会发生这种情况? Also, the first 8 values are printed 2 at a time every 1 second, but for the last 2 values there is a 1-second pause as well between them. 同样,前8个值每1秒一次打印2次,但是对于后2个值,它们之间也有1秒的暂停。 To clarify this, let me draw 1-sec pauses as hyphens: 为了澄清这一点,让我绘制1秒的暂停作为连字符:

0
0
-
1
1
-
0
0
-
1
1
-
0
-
1

Why is this happening? 为什么会这样呢?

Thanks a lot. 非常感谢。

Processes do not share memory. 进程不共享内存。

In your example, each and every process works on its own copy of the deque. 在您的示例中,每个进程都在自己的双端队列副本上工作。 There is no synchronization between them at all. 它们之间根本没有同步。

You can use a multiprocessing.Queue object to achieve the correct result. 您可以使用multiprocessing.Queue对象来获得正确的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM