Sunday 20 December 2015

Python: starmap: Pass multiple arguments

starmap(func, iterable[, chunksize])

Just like map, by using this we can pass multiple arguments to a function. Hence an iterable of [(1,2), (3, 4)] results in [func(1,2), func(3,4)].
from multiprocessing import Pool, Process
from time import sleep
import os


def sum(task, a, b):
    return a+b

if __name__=="__main__":
    myPool = Pool(5)

    tasks=[]

    for i in range(10):
        tuple=("task"+str(i), i+10, i+20)
        tasks.append(tuple)

    print(tasks)

    print("Submitted tasks to pool")
    results = myPool.starmap(sum, tasks)
    print("Got the results")

    for result in results:
        print(result)


Output
[('task0', 10, 20), ('task1', 11, 21), ('task2', 12, 22), ('task3', 13, 23), ('task4', 14, 24), ('task5', 15, 25), ('task6', 16, 26), ('task7', 17, 27), ('task8', 18, 28), ('task9', 19, 29)]
Submitted tasks to pool
Got the results
30
32
34
36
38
40
42
44
46
48



Previous                                                 Next                                                 Home

No comments:

Post a Comment