Home >Backend Development >Python Tutorial >How to Retrieve Return Values from Multiprocessing.Process Functions in Python?

How to Retrieve Return Values from Multiprocessing.Process Functions in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 19:07:26547browse

How to Retrieve Return Values from Multiprocessing.Process Functions in Python?

Access Return Value of a Function in Multiprocessing.Process

In multiprocessing with Python, obtaining the return value of a function passed to multiprocessing.Process can be tricky, as it is not stored directly in the Process object.

Consider the following example:

import multiprocessing

def worker(procnum):
    '''worker function'''
    print(str(procnum) + ' represent!')
    return procnum


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

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

While this code prints the output of each worker process, we cannot directly access their return values.

To retrieve the return values, we can employ a shared variable. In the following revised code, a Manager() from the multiprocessing module is used to create a shared dictionary:

import multiprocessing


def worker(procnum, return_dict):
    """worker function"""
    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())

Here, each worker process updates the shared dictionary return_dict with its return value. The main process can then access these values from the shared dictionary.

The above is the detailed content of How to Retrieve Return Values from Multiprocessing.Process Functions in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn