How Do You Write a Python Program to Create New Processes with the multiprocessing Library?

Problem scenario
You want to create new processes with the multiprocessing library in Python. What should you do?

Solution
Run this program:

""" In a duplicate terminal window, run this command before, during and after you run the pyhon script:  sudo ps -ef | grep python | wc -l

The integer that returns will go up by two showing a new processes have been created when the program is still running.  The integer value will return to what it was after the Python program stops.
"""

from multiprocessing import Process
import os
import time

def mp_demonstrate(title):
    print(title)
    print('module name:', __name__)
    if hasattr(os, 'getppid'):  # only available on Linux or Unix
        print('The parent process ID is :', os.getppid())
    print ('The process ID is:', os.getpid())
    time.sleep(1)

def basicfunction(name):
    mp_demonstrate('This is inside basicfunction')
    print('Goodbye', name)
    time.sleep(1)

if __name__ == '__main__':
    mp_demonstrate('This program illustrates process IDs')
    time.sleep(1)
    p = Process(target=basicfunction, args=('user',))
    p.start()
    time.sleep(1)
    p.join(1) # The timeout value is one second.  It will timeout if it has to wait more than this.
    # The join() method for a process is different from "join" when dealing with a string or list.

Leave a comment

Your email address will not be published. Required fields are marked *