Python multiprocessing lock strange behavior
<p>I notice a behaviour in my code that I cannot explain. This is the code:</p>

<pre><code>import multiprocessing
from collections import deque

LOCK = multiprocessing.Lock()

data = deque(['apple', 'orange', 'melon'])

def f(*args):
    with LOCK:
        data.rotate()
        print data[0]

pool = multiprocessing.Pool()
pool.map(f, range(4))
</code></pre>

<p>I expect that the output would be </p>

<pre><code>melon
orange
apple
melon
</code></pre>

<p>but instead I get</p>

<pre><code>melon
melon
melon
</code></pre>

<p>Any ideas would be greatly appreciated.</p>

<p>As Tim Peters commented, the problem is not the <code>Lock</code> but that the <code>deque</code> is not shared across the processes but every process will have their own copy.</p>

<p>There are some data structures provided by the <code>multiprocessing</code> module which will be shared across processes, e.g. <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue" rel="nofollow"><code>multiprocessing.Queue</code></a>. Use that instead.</p>

python multiprocessing python-multiprocessing