This is my simple code where I want to run printRange() in parallel:
JavaScript
x
8
1
def printRange(lrange):
2
print ("First is " + str(lrange[0]) + " and last is " + str(lrange[1]))
3
4
5
def runInParallel():
6
ranges = [[0, 10], [10, 20], [20, 30]]
7
// Call printRange in parallel with each sublist of ranges given as argument
8
My question is different from this SO question as here, the each process is hardcoded, started and finally joined. I want to run printRange() in parallel with say 100 other printRange() worker functions. Hardcoding each time is not feasible. How could this be done?
Advertisement
Answer
Using multiprocessing
JavaScript
1
16
16
1
from multiprocessing import Pool
2
3
4
def print_range(lrange):
5
print('First is {} and last is {}'.format(lrange[0], lrange[1]))
6
7
8
def run_in_parallel():
9
ranges = [[0, 10], [10, 20], [20, 30]]
10
pool = Pool(processes=len(ranges))
11
pool.map(print_range, ranges)
12
13
14
if __name__ == '__main__':
15
run_in_parallel()
16
Output:
JavaScript
1
4
1
First is 0 and last is 10
2
First is 10 and last is 20
3
First is 20 and last is 30
4