Lakshanth C
Lakshanth C

Reputation: 95

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

Upvotes: 0

Views: 9206

Answers (2)

You can use Queue from multiprocessing, then pass it to print_cube() as shown below:

from multiprocessing import Process, Queue

def print_cube(num, q): 
    aa1 = num * num * num
    q.put(aa1)

def main(): 
    queue = Queue()
    p1 = Process(target=print_cube, args=(10, queue)) 
    p1.start() 
    print(queue.get()) # 1000
    
main()

This is the result below:

1000

Be careful, if using queue module below with process, the program doesn't work properly:

import queue
queue = queue.Queue()

So, just use Queue from multiprocessing module with process as I used in the code above:

from multiprocessing import Queue
queue = Queue()

Upvotes: 1

Satish
Satish

Reputation: 3100

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

Upvotes: 2

Related Questions