getting the return value of a function used in multiprocess

Question:

Say I have the below code, a function that does something, which is initiated in a Process, and returns a value.

from multiprocessing import Process

def my_func(arg):
    return 'Hello, ' + arg

p1 = Process(target=my_func, args=('John',)
p1.start()
p1.join()

How do I get the return value of the function?

Asked By: Ari

||

Answers:

Answer

from multiprocessing import Process, Queue

Q = Queue()

def my_func(arg):
    Q.put('Hello, ' + arg)

p1 = Process(target=my_func, args=('John',))
p1.start()
print(Q.get())
p1.join()
Answered By: Ari

You can pass Queue of multiprocessing to my_func() as shown below:

from multiprocessing import Process, Queue

def my_func(arg, q):
    q.put('Hello, ' + arg)
    
queue = Queue()                            # Here
p1 = Process(target=my_func, args=('John', queue))
p1.start()
print(queue.get())
p1.join()

This is the result below:

Hello, John

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

import queue
queue = queue.Queue()

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

from multiprocessing import Queue
queue = Queue()
Answered By: Kai – Kazuya Ito