getting the return value of a function used in multiprocess
Asked Answered
G

2

13

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?

Godber answered 10/2, 2019 at 10:33 Comment(2)
Possible duplicate of How can I recover the return value of a function passed to multiprocessing.Process?Gokey
This might help: docs.python.org/2/library/…Loverly
G
17

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()
Godber answered 20/8, 2019 at 23:4 Comment(2)
Please add the missing brackets: Queue(), Process(target=my_func, args=('John',)).Ullund
This implies to modify your original my_func adding Q if you want to use it parallelBarrier
C
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()
Coralline answered 10/11, 2022 at 2:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.