Skip to content

Multiprocessing

Farrokh Karimi edited this page Aug 12, 2018 · 8 revisions

Previous Page

In this section, we will focus more on the comparison between multiprocessing and multithreading.

Multiprocessing: It is the use of two or more CPUs units within a single computer system. It is the best approach to get the full potential from our hardware by utilizing full number of CPU cores available in our computer system.

Multithreading: It is the ability of a CPU to manage the use of operating system by executing multiple threads concurrently. The main idea of multithreading is to achieve parallelism by dividing a process into multiple threads.

The following table shows some of the important differences between them:

Multiprocessing Multiprogramming
1 Multiprocessing refers to processing of multiple processes at same time by multiple CPUs. Multiprogramming keeps several programs in main memory at the same time and execute them concurrently utilizing single CPU.
2 It utilizes multiple CPUs. It utilizes single CPU.
3 It permits parallel processing. Context switching takes place.
4 Less time taken to process the jobs. More Time taken to process the jobs.
5 It facilitates much efficient utilization of devices of the computer system. Less efficient than multiprocessing.
6 Usually more expensive. Such systems are less expensive.

Eliminating impact of GIL

While working with concurrent applications, there is a limitation present in Python called the GIL (Global Interpreter Lock). GIL never allows us to utilize multiple cores of CPU and hence we can say that there are no true threads in Python. GIL is the mutex – mutual exclusion lock, which makes things thread safe. In other words, we can say that GIL prevents multiple threads from executing Python code in parallel. The lock can be held by only one thread at a time and if we want to execute a thread then it must acquire the lock first. With the use of multiprocessing, we can effectively bypass the limitation caused by GIL:

  • By using multiprocessing, we are utilizing the capability of multiple processes and hence we are utilizing multiple instances of the GIL.
  • Due to this, there is no restriction of executing the bytecode of one thread within our programs at any one time.

Starting Processes in Python

The following three methods can be used to start a process in Python within the multiprocessing module:

  • Fork
  • Spawn
  • Forkserver

Fork

In computing, particularly in the context of the Unix operating system and its workalikes, fork is an operation whereby a process creates a copy of itself. It is usually a system call, implemented in the kernel. Fork is the primary (and historically, only) method of process creation on Unix-like operating systems.

Creating a process with Fork

Fork command is a standard command found in UNIX. It is used to create new processes called child processes. This child process runs concurrently with the process called the parent process. These child processes are also identical to their parent processes and inherit all of the resources available to the parent. The following system calls are used while creating a process with Fork:

  • fork(): It is a system call generally implemented in kernel. It is used to create a copy of the process.
  • getpid(): This system call returns the process ID(PID) of the calling process.

Example: The following Python script example will help you understabd how to create a new child process and get the PIDs of child and parent processes:

import os

def child():
   n = os.fork()
   
   if n > 0:
      print("PID of Parent process is : ", os.getpid())

   else:
      print("PID of Child process is : ", os.getpid())

child()

Output:

PID of Parent process is : 25989
PID of Child process is : 25990

Creating a process with Spawn

Spawn means to start something new. Hence, spawning a process means the creation of a new process by a parent process. The parent process continues its execution asynchronously or waits until the child process ends its execution. Follow these steps for spawning a process:

  • Importing multiprocessing module.
  • Creating the object process.
  • Starting the process activity by calling start() method.
  • Waiting until the process has finished its work and exit by calling join() method.

Example: The following example of Python script helps in spawning three processes:

import multiprocessing

def spawn_process(i):
    print ('This is process: %s' %i)
    return

if __name__ == '__main__':
    Process_jobs = []
    for i in range(3):
        p = multiprocessing.Process(target = spawn_process(i), args = (i,))
        print(p)
        Process_jobs.append(p)
    p.start()
    p.join()

Output:

This is process: 0
<Process(Process-136, initial)>
This is process: 1
<Process(Process-137, initial)>
This is process: 2
<Process(Process-138, initial)>

Creating a process with Forkserver

Forkserver mechanism is only available on those selected UNIX platforms that support passing the file descriptors over Unix Pipes. Consider the following points to understand the working of Forkserver mechanism:

  • A server is instantiated on using Forkserver mechanism for starting new process.
  • The server then receives the command and handles all the requests for creating new processes.
  • For creating a new process, our python program will send a request to Forkserver and it will create a process for us.
  • At last, we can use this new created process in our programs.

Daemon

In multitasking computer operating systems, a daemon (/ˈdiːmən/ or /ˈdeɪmən/) is a computer program that runs as a background process, rather than being under the direct control of an interactive user. Traditionally, the process names of a daemon end with the letter d, for clarification that the process is, in fact, a daemon, and for differentiation between a daemon and a normal computer program. For example, syslogd is the daemon that implements the system logging facility, and sshd is a daemon that serves incoming SSH connections.

In a Unix environment, the parent process of a daemon is often, but not always, the init process. A daemon is usually either created by a process forking a child process and then immediately exiting, thus causing init to adopt the child process, or by the init process directly launching the daemon. In addition, a daemon launched by forking and exiting typically must perform other operations, such as dissociating the process from any controlling terminal (tty). Such procedures are often implemented in various convenience routines such as daemon(3) in Unix.

Systems often start daemons at boot time which will respond to network requests, hardware activity, or other programs by performing some task. Daemons such as cron may also perform defined tasks at scheduled times.

Daemon processes in Python

Python multiprocessing module allows us to have daemon processes through its daemonic option. Daemon processes or the processes that are running in the background follow similar concept as the daemon threads. To execute the process in the background, we need to set the daemonic flag to true. The daemon process will continue to run as long as the main process is executing and it will terminate after finishing its execution or when the main program would be killed.

Example:

import multiprocessing
import time

def daemonProcess():
    for i in range (20):
        print("Daemon process")
        time.sleep(1)
        
if __name__ == '__main__':
    daemonProcess = multiprocessing.Process(target = daemonProcess)
    daemonProcess.daemon = True
    for i in range (5):
        print("Non daemon process")
        time.sleep(1)
    daemonProcess.start()

Terminating processes in Python

We can kill or terminate a process immediately by using the terminate() method. We will use this method to terminate the child process, which has been created with the help of function, immediately before completing its execution.

Terminating processes in Python

We can kill or terminate a process immediately by using the terminate() method. We will use this method to terminate the child process, which has been created with the help of function, immediately before completing its execution.

Example:

import multiprocessing
import time
def Child_process():
   print ('Starting function')
   time.sleep(5)
   print ('Finished function')
P = multiprocessing.Process(target = Child_process)
P.start()
time.sleep(2)
print("Terminating Child Process")
P.terminate()
print("Child Process successfully terminated")

Output:

Starting function
Terminating Child Process
Child Process successfully terminated

The output shows that the program terminates before complete execution of child process that has been created with the help of the Child_process() function. This implies that the child process has been terminated successfully.

Identifying the current process in Python

Every process in the operating system is having process identity known as PID. In Python, we can find out the PID of current process with the help of the following command:

Example: The following example of Python script helps find out the PID of main process as well as PID of child process:

import multiprocessing
import time
def Child_process():
   print("PID of Child Process is: {}".format(multiprocessing.current_process().pid))
print("PID of Main process is: {}".format(multiprocessing.current_process().pid))
P = multiprocessing.Process(target=Child_process)
P.start()
P.join()

Output:

PID of Main process is: 26138
PID of Child Process is: 26173

Using a process in subclass

Clone this wiki locally