DEV Community

Rifat977
Rifat977

Posted on • Edited on

Thread vs. Process: Explore Multi-threading and Multiprocessing with python

Before delving into multi-threading and multi-processing, it's essential to understand concurrency and parallelism because these foundational concepts provide the basis for comprehending and implementing these specific techniques in software development.

Image description

Concurrency:

Imagine a restaurant with a single chef who can efficiently handle orders from two tables. The chef switches between the tables, taking orders, cooking dishes, and serving them. While the chef cannot cook for both tables at the exact same time, they manage to overlap their tasks, so it seems as if both tables are being served simultaneously. This concept reflects concurrency, where multiple tasks are handled with overlapping execution on a single chef's workstation.

Parallelism:

In contrast, parallelism is like having two chefs in the kitchen, each exclusively responsible for their own table of customers. Both chefs work independently, preparing and serving dishes for their respective tables simultaneously. This is made possible because there are two chefs working in parallel, taking full advantage of the available workforce to expedite service and enhance efficiency.

Image description

Multiprocessing:

Multiprocessing means using more than one computer brain (processor) to make a computer work faster. It's like having multiple workers doing different jobs at the same time, which makes the computer run better and faster. Here is a example of multiprocessing using python -

import multiprocessing

def process1(name):
    print(f"Hello, {name}!")

def process2(name):
    print(f"Goodbye, {name}!")

p1 = multiprocessing.Process(target=process1, args=['Abdullah'])
p2 = multiprocessing.Process(target=process2, args=['Rifat'])

p1.start()
p2.start()

p1.join()
p2.join()
Enter fullscreen mode Exit fullscreen mode

#### Output
Hello, Abdullah!
Goodbye, Rifat!

We then create two processes using the multiprocessing.Process class, passing in the functions and their respective arguments.

Multi-threading:

Multi-threading is like one worker doing multiple tasks at the same time, sharing the same brain (processor). It helps a computer run more efficiently by handling different jobs simultaneously, improving performance. Here is a example of multi-threading using python -

import threading
import time

def worker():
    print("Worker started")
    time.sleep(1)
    print("Worker finished")

t1 = threading.Thread(target=worker)
t2 = threading.Thread(target=worker)

t1.start()
t2.start()

Enter fullscreen mode Exit fullscreen mode

Output

Worker started
Worker started
Worker finished
Worker finished

This code creates 2 threads using the threading.Thread class and starts them all using the start() method. We can also create multiple threads using loop.

Top comments (0)