Search code examples
pythonpython-multiprocessing

How to get the return value of a function in multiprocessing code


This is my python code. I am trying to get the returned value(aa1) from the print_cube() Is there a way to get the value of aa1 inside the main(). I have to use multiprocessing to call other functions also.

import multiprocessing   
def print_cube(num): 
    aa1 = num * num * num
    return aa1

def main(): 
    # creating processes 
    p1 = multiprocessing.Process(target=print_cube, args=(10, )) 
    p1.start() 

main()

Solution

  • Use multiprocessing.Pool when you want to retrieve return values.

    def print_cube(num):
        aa1 = num * num * num
        return aa1
    
    
    def main():
        with Pool(5) as p:
            results = p.map(print_cube, range(10, 15))
        print(results)
    
    
    if __name__ == "__main__":
        main()