Multithreading and Multiprocessing in Python

 Multithreading and Multiprocessing 

Multithreading and multiprocessing are two techniques used  for achieving concurrency, which is the ability of a program to execute multiple tasks simultaneously. However, they operate differently and have distinct use cases.

Multithreading:

Multithreading is a technique where multiple threads within a process share the same memory space.

Threads are lighter than processes and are suitable for I/O-bound tasks such as network communication or disk I/O.

Python's threading module provides a way to create and manage threads. However, due to the Global Interpreter Lock (GIL), Python threads are not suitable for CPU-bound tasks that require parallel execution of CPU-intensive operations.

Example:

Python Code

 import threading


def print_numbers():

    for i in range(1, 6):

        print(i)


def print_letters():

    for letter in 'ABCDE':

        print(letter)


t1 = threading.Thread(target=print_numbers)

t2 = threading.Thread(target=print_letters)


t1.start()

t2.start()


t1.join()

t2.join()

Multiprocessing:

Multiprocessing, on the other hand, involves running multiple processes simultaneously, each with its own memory space. This allows true parallelism as each process runs independently of the others.

Python's multiprocessing module allows you to create and manage processes. It's suitable for CPU-bound tasks that benefit from parallel execution, as it bypasses the GIL.

Example:

Python Code

 import multiprocessing


def square(n):

    return n * n


if __name__ == '__main__':

    numbers = [1, 2, 3, 4, 5]


    # Create a pool of processes

    with multiprocessing.Pool() as pool:

        # Map the `square` function to each element in `numbers`

        results = pool.map(square, numbers)


    print(results)

In summary, use multithreading when dealing with I/O-bound tasks and multiprocessing for CPU-bound tasks. Be cautious when using multiprocessing, as it incurs more overhead due to process creation and inter-process communication.

 


Post a Comment

Previous Post Next Post