Easiest way to parallelise a call to map?
<p>Hey I have some code in Python which is basically a World Object with Player objects. At one point the Players all get the state of the world and need to return an action. The calculations the players do are independent and only use the instance variables of the respective player instance.</p>

<pre><code>while True:
    #do stuff, calculate state with the actions array of last iteration
    for i, player in enumerate(players):
        actions[i] = player.get_action(state)
</code></pre>

<p>What is the easiest way to run the inner <code>for</code> loop parallel? Or is this a bigger task than I am assuming?</p>

<p>The most straightforward way is to use <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map" rel="nofollow">multiprocessing.Pool.map</a> (which works just like <code>map</code>):</p>

<pre><code>import multiprocessing
pool = multiprocessing.Pool()

def do_stuff(player):
    ...  # whatever you do here is executed in another process

while True:
    pool.map(do_stuff, players)
</code></pre>

<p>Note however that this uses multiple processes. There is no way of doing multithreading in Python due to the <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">GIL</a>.</p>

<p>Usually parallelization is done with threads, which can access the same data inside your program (because they run in the same process). To share data between processes one needs to use IPC (inter-process communication) mechanisms like pipes, sockets, files etc. Which costs more resources. Also, spawning processes is much slower than spawning threads.</p>

<p>Other solutions include:</p>

<ul>
<li>vectorization: rewrite your algorithm as computations on vectors and matrices and use hardware accelerated libraries to execute it</li>
<li>using another Python distribution that doesn't have a GIL</li>
<li>implementing your piece of parallel code in another language and calling it from Python</li>
</ul>

<p>A big issue comes when your have to share data between the processes/threads. For example in your code, each task will access <code>actions</code>. If you <em>have</em> to share state, welcome to <a href="https://en.wikipedia.org/wiki/Concurrent_computing" rel="nofollow">concurrent programming</a>, a much bigger task, and one of the hardest thing to do right in software.</p>

python python-3.x parallel-processing