Categories
Python Answers

How to get the return value of a function passed to Python multiprocessing.Process?

Spread the love

Sometimes, we want to get the return value of a function passed to Python multiprocessing.Process.

In this article, we’ll look at how to get the return value of a function passed to Python multiprocessing.Process.

How to get the return value of a function passed to Python multiprocessing.Process?

To get the return value of a function passed to Python multiprocessing.Process, we can use the manager.dict method to create a shared variable.

For instance, we write

import multiprocessing


def worker(procnum, return_dict):
    print(str(procnum) + " represent!")
    return_dict[procnum] = procnum


if __name__ == "__main__":
    manager = multiprocessing.Manager()
    return_dict = manager.dict()
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i, return_dict))
        jobs.append(p)
        p.start()

    for proc in jobs:
        proc.join()
    print(return_dict.values())

to create a Process object with the target set to the worker function that runs for each process.

Then we set the args to a tuple with the arguments for worker.

Then we call jobs.append to append the process p to jobs.

And then we call p.start to start the process.

Next, we have a for loop that calls join to block the main process from running until the proc process terminates.

And then we get the returned values of worker with return_dict.values().

Conclusion

To get the return value of a function passed to Python multiprocessing.Process, we can use the manager.dict method to create a shared variable.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *