Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - parallel commands

Tags:

python

How do I run several python commands in parallel in a python script ? As a simple example I have several sleep commands:

time.sleep(4)
time.sleep(6)
time.sleep(8)

I want all the above to be executed in parallel. I expect the control back when 8 seconds have passed (which is the max of all the sleeps above). The real commands will be different but want to get an idea with above.

In bash, I could have simple done:

sleep 4 &
pid1=$!
sleep 6 &
pid2=$!
sleep 8 &
pid3=$!
wait $pid1 $pid2 $pid3

Thanks.

like image 935
A J Avatar asked Aug 23 '12 17:08

A J


People also ask

How do I run a parallel command in Python?

To do this, you initialize a Pool with n number of processors and pass the function you want to parallelize to one of Pool s parallization methods. multiprocessing. Pool() provides the apply() , map() and starmap() methods to make any function run in parallel.

Can Python be used for parallel programming?

There are several common ways to parallelize Python code. You can launch several application instances or a script to perform jobs in parallel. This approach is great when you don't need to exchange data between parallel jobs.

What does parallel mean Python?

What is Parallelization in Python? Parallelization in Python (and other programming languages) allows the developer to run multiple parts of a program simultaneously. Most of the modern PCs, workstations, and even mobile devices have multiple central processing unit (CPU) cores.


1 Answers

One simple example, using multiprocessing:

import multiprocessing as mp
import time

pool = mp.Pool(3)
results = pool.map(time.sleep, [4, 6, 8] )

This spawns separate processes instead of creating separate threads in the same process as demonstrated in the answer by Steven Rumbalski. multiprocessing sidesteps the GIL (in cpython) meaning that you can execute python code simultaneously (which you can't do in cpython with threading). However, it has the downside that the information you send to the other processes must be pickleable, and sharing state between processes is a bit more complicated as well (although I could be wrong about the last point -- I've never really used threading).

word of caution: Don't try this in the interactive interpreter

like image 54
mgilson Avatar answered Oct 12 '22 22:10

mgilson