The following steps allow us to perform the recipe:
- Let's import the relevant libraries:
import multiprocessing
import time
- Then, a simple target function is implemented. In this example, the target function, foo(), prints the first 10 digits:
def foo():
print ('Starting function')
for i in range(0,10):
print('-->%d ' %i)
time.sleep(1)
print ('Finished function')
- In the main program, we create a process monitoring its lifetime by the is_alive method; then, we finish it with a call to terminate:
if __name__ == '__main__':
p = multiprocessing.Process(target=foo)
print ('Process before execution:', p, p.is_alive())
p.start()
print ('Process running:', p, p.is_alive())
p.terminate()
print ('Process terminated:', p, p.is_alive())
p.join()
print ('Process joined:', p, p.is_alive())
- Then, we verify the status code when the process is finished and read the attribute of the ExitCode process:
print ('Process exit code:', p.exitcode)
- The possible values of ExitCode are as follows:
- == 0: No error was produced.
- > 0: The process had an error and exited that code.
- < 0: The process was killed with a signal of -1 * ExitCode.