0

How to return data from a function called by multiprocessing.Process

Here I have a code in a file named thread_killer.py

from multiprocessing import Process
import time


def do_actions():
    i = 1
    # doing some long operation, if this operation will be done at less than 4 sec then it will return i to main() function
    while True:

        print(i)
        if i>2:
            break
        i += 1
        time.sleep(1)
    return "111" # this is my return 


def main(time_out):
    action_process = Process(target=do_actions)
    
    action_process.start() # Start the process which will be killed after "time_out" seconds.
    
    action_process.join(timeout=time_out)

    action_process.terminate()
    print("Timed is out.")

    return # Here I need to return "111" from do_actions function


if __name__ == '__main__':
    main(time_out)

And this is the file where I'm calling thread_killer:

import thread_killer as tkl

if __name__ ==  '__main__':
    xxx = tkl.main(4)  
# (4) is amount of seconds after which thread called by multiprocessing.Process will be killed 
    print(xxx, "This is my return from do_actions() function passed to the main() function if the do_actions() function was fast and finished its job faster than if was terminated")

So, I need to return "111" from do_actions() function when I'm running xxx = tkl.main(4) How to make this work?

Nick PV
  • 415
  • 6
  • 14
  • Are you limited to using `multiprocessing.Process`? Because if not, `concurrent.futures` gives you the ability to get the return value of whatever is run in the process. – PyPingu Jan 02 '20 at 10:23
  • 2
    Does this answer your question? [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) – Ramon Medeiros Jan 02 '20 at 10:55
  • @RamonMedeiros `manager = multiprocessing.Manager() return_dict = manager.dict()` **works**. Thanks. I will mark this a duplicate then. – Nick PV Jan 06 '20 at 18:38

0 Answers0