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:
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!