Python multiprocessing return value

Python Multiprocessing Return Value

In Python, the multiprocessing module is used to spawn processes and run them concurrently. One common use case is to execute functions or methods in parallel and retrieve their return values.

When using the multiprocessing.Pool class, which provides a convenient way to parallelize function execution, you can obtain the return values using the apply or map methods.

1. Using apply method

The apply method allows you to execute a function asynchronously in a separate process and retrieve its return value. Here’s an example:

    import multiprocessing

    def square(x):
        return x**2

    if __name__ == "__main__":
        pool = multiprocessing.Pool()
        result = pool.apply(square, (5,))
        print(result)
    

In this example, we define a function square that takes an argument x and returns its square. We create a multiprocessing.Pool object and use the apply method to apply the square function to the argument 5. The return value of the apply method is stored in the result variable and printed. This will output 25.

2. Using map method

The map method allows you to execute a function asynchronously in parallel on multiple inputs and retrieve the corresponding return values. Here’s an example:

    import multiprocessing

    def square(x):
        return x**2

    if __name__ == "__main__":
        pool = multiprocessing.Pool()
        numbers = [1, 2, 3, 4, 5]
        results = pool.map(square, numbers)
        print(results)
    

In this example, we define the same square function as before. We create a multiprocessing.Pool object and use the map method to apply the square function to each element of the numbers list. The return values are stored in the results list and printed. This will output [1, 4, 9, 16, 25].

Leave a comment