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

How to Retrieve Return Values from multiprocessing.Process Functions?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-29 06:30:12850browse

How to Retrieve Return Values from multiprocessing.Process Functions?

How to Retrieve Return Values from Functions Passed to multiprocessing.Process

When passing a function to multiprocessing.Process, there's often a need to retrieve the function's return value. However, these values are not readily accessible in the returned Process objects.

Consider the following code:

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

The expected return values are not available through the Process objects in 'jobs'.

Solution: Using a Shared Variable

To retrieve the return values, a shared variable can be utilized to enable communication between the main process and worker processes.

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())

Explanation:

  • A multiprocessing Manager is used to create the shared dictionary, 'return_dict'.
  • Each worker process accesses the shared 'return_dict' and stores its return value under its process number as the key.
  • The main process retrieves the return values by accessing the dictionary's values.

The above is the detailed content of How to Retrieve Return Values from multiprocessing.Process Functions?. 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