How it works...

In this section, we have therefore seen how it is possible to create processes by starting from a parent process. This feature is called spawning a process

Python's multiprocessing library allows easy process management by following three simple steps. The first step is the process definition through the multiprocessing class method, Process:

process = multiprocessing.Process(target=myFunc, args=(i,))

The Process method has as an argument of the function to spawn, myFunc, and any arguments of the function itself.

The following two steps are necessary to execute and exit the process:

     process.start()
process.join()

To run the process and display the results, let's open Command Prompt, preferably in the same folder containing the example file (spawning_processes.py), and then type the following command:

> python spawning_processes.py

For each process created (there are six in all), the output of the target function is shown. Remember that this is a simple counter from 0 up to the index of the process ID:

calling myFunc from process n°: 0
calling myFunc from process n°: 1
output from myFunc is :0
calling myFunc from process n°: 2
output from myFunc is :0
output from myFunc is :1
calling myFunc from process n°: 3
output from myFunc is :0
output from myFunc is :1
output from myFunc is :2
calling myFunc from process n°: 4
output from myFunc is :0
output from myFunc is :1
output from myFunc is :2
output from myFunc is :3
calling myFunc from process n°: 5
output from myFunc is :0
output from myFunc is :1
output from myFunc is :2
output from myFunc is :3
output from myFunc is :4
..................Content has been hidden....................

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