We are onto our final Python module,
multiprocessing. This module is unique from
asyncio in that allows the user to leverage multiple processors on a given machine simultaneously. This is because instead of threads or asynchronous tasks,
multiprocessing is powered by subprocesses.
Implementation will look very similar to how we approached the
We went over processes in the previous lesson; now we are going to implement them in Python.
To create a process in Python, we do the following:
import multiprocessing p = multiprocessing.Process(target=target_function, args=(arg,))
This might look familiar as the arguments are identical.
target is the function we execute with the process and
args is the argument or set of arguments used in the function.
Also identical to the threading module, to start the process, we use:
Let’s practice with an example!
Let’s try running
greeting_with_sleep() with a single process.
Create a process object called
p. This process should execute
'Codecademy' as the argument.
Inside the terminal output, type
python3 script.py and press Enter. To check your answer, click Check Work once your program finishes running.