Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python multiprocessing with boolean and multiple arguments

I have a function that takes multiple arguments, some of which are boolean. I'm trying to pass this to the multiprocessing pool.apply_async and want to pass some args with the names attached.

Here's an example script that I'm working with:

from multiprocessing import Pool

    def testFunc(y, x, calcY=True):
        if calcY == True:
            return y*y
        elif calcY == False:
            return x*x

    if __name__ == "__main__":
        p = Pool()
        res = p.apply_async(testFunc, args = (2, 4, False))
        print res.get()

This works, but I'm curious about changing the res = p.apply_async(testFunc, args = (2, 4, False)) to something like:

res = p.apply_async(testFunc, args = (2, 4, calcY = False))
like image 656
user1074057 Avatar asked Sep 18 '12 18:09

user1074057


People also ask

How do you pass multiple arguments in multiprocessing Python?

Use Pool. The multiprocessing pool starmap() function will call the target function with multiple arguments. As such it can be used instead of the map() function. This is probably the preferred approach for executing a target function in the multiprocessing pool that takes multiple arguments.

What is multiprocess in Python?

multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads.

What is pool in multiprocessing Python?

Python multiprocessing Pool can be used for parallel execution of a function across multiple input values, distributing the input data across processes (data parallelism). Below is a simple Python multiprocessing Pool example.


1 Answers

apply_async has args and kwds keyword arguments which you could use like this:

res = p.apply_async(testFunc, args=(2, 4), kwds={'calcY': False})
like image 186
unutbu Avatar answered Oct 01 '22 05:10

unutbu