getting the return value of a function used in multiprocess

15,213

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()
Share:
15,213
Ari
Author by

Ari

Staying curious.

Updated on June 12, 2022

Comments

  • Ari
    Ari almost 2 years

    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?

  • spaenigs
    spaenigs over 4 years
    Please add the missing brackets: Queue(), Process(target=my_func, args=('John',)).
  • leonard vertighel
    leonard vertighel over 2 years
    This implies to modify your original my_func adding Q if you want to use it parallel