1

I have some code that does the following:

  • Creates a process (process is solvePuzzle(filename))
  • Runs the process
  • If the process finishes within timeLimit, do something
  • If the process times out, do something else

My issue is with the third task; I want to be able to get the return value of the function that was processed. Here is my code (I made up the statement p.returnValue() as this is what I'm trying to do):

    #Start process
    p = multiprocessing.Process(target=globals()['solvePuzzle'], args=(filename,))        
    p.start()

    #Wait for timeLimit seconds or until process finishes
    p.join(timeLimit)

    #If thread is still active
    if p.is_alive():
        print "Puzzle timed out after " + str(timeLimit) + " seconds!"

        # Terminate
        p.terminate()
        p.join()
    else:
        print "Solution = " + str(p.returnValue())
Ashley
  • 487
  • 7
  • 19
  • How about using a Queue for sending the result back to the main process? – Javier Apr 19 '15 at 00:31
  • See [this question](http://stackoverflow.com/questions/7194884/assigning-return-value-of-function-to-a-variable-with-multiprocessing-and-a-pr) for an example that shows how you can get the return value back to the parent. – dano Apr 19 '15 at 00:58

1 Answers1

-1

A process has an exit code. This is generally used in linux to indicate if the job was successful. A return code of '0' indicates success. The return code of the process can be got using the following changes in your code.

import multiprocessing
import time
timeLimit = 200
#Start process
def start():
    p = multiprocessing.Process(target=time.sleep, args=(10,))
    p.start()

    #Wait for timeLimit seconds or until process finishes
    p.join(timeLimit)

    #If thread is still active
    if p.is_alive():
        print "Puzzle timed out after " + str(timeLimit) + " seconds!"

        # Terminate
        p.terminate()
        p.join()
    else:
        print "Solution = " + str(p.exitcode)

start()

If you have an integer that you want to return from the process, you can use this method. If you have some other type of value (for e.g. string) that you are trying to get back, then you need to use Queue. Check out example at http://pymotw.com/2/multiprocessing/communication.html