Search code examples
pythonpython-multiprocessing

getting the return value of a function used in multiprocess


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?


Solution

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