How to do it...

The following steps allow us to perform the recipe:

  1. Let's import the relevant libraries:
import multiprocessing
import time
  1. 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')
  1. 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())
  1. 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)
  1. 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.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.189.247