12

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ari
  • 5,301
  • 8
  • 46
  • 120
  • 3
    Possible duplicate of [How can I recover the return value of a function passed to multiprocessing.Process?](https://stackoverflow.com/questions/10415028/how-can-i-recover-the-return-value-of-a-function-passed-to-multiprocessing-proce) – Jan Christoph Terasa Feb 10 '19 at 10:40
  • This might help: https://docs.python.org/2/library/multiprocessing.html#exchanging-objects-between-processes – e.dan Feb 10 '19 at 10:43

2 Answers2

16

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()
Ari
  • 5,301
  • 8
  • 46
  • 120
0

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()
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129