Critical Section — Explained with Examples
A critical section is a block of code that accesses shared resources and must not be executed by multiple threads simultaneously.
Critical sections are protected by synchronization primitives (mutexes, semaphores) to ensure mutual exclusion. Only one thread executes the critical section at a time. The section should be as short as possible to minimize contention. Key patterns: entry section (acquire lock), critical section (access shared resource), exit section (release lock), and remainder section (other work).
Think of a critical section like the single checkout lane at a small store. The area between the entrance barrier and the exit gate is the critical section. Only one customer (thread) can be in that area at a time. The customer enters (acquires lock), pays (executes critical code), and leaves (releases lock). Other customers wait outside.
Identifying critical sections is the first step in making code thread-safe. Race conditions occur when shared resource access happens outside a critical section without proper protection.
import threading
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
self.lock = threading.Lock()
def transfer(self, amount, to_account):
# Identify critical sections
with self.lock: # Entry section
# START critical section
if self.balance >= amount:
self.balance -= amount
to_account.deposit(amount)
print(f"Transferred {amount}")
else:
print("Insufficient funds")
# END critical section
# Exit section (automatic via 'with')
def deposit(self, amount):
with self.lock: # Entry section
self.balance += amount # Critical section
# Exit section
def get_balance(self):
with self.lock: # Reading also needs protection
return self.balance
alice = BankAccount(1000)
bob = BankAccount(500)
def make_transfer():
alice.transfer(200, bob)
threads = [threading.Thread(target=make_transfer) for _ in range(5)]
for t in threads: t.start()
for t in threads: t.join()
print(f"Alice: {alice.get_balance()}, Bob: {bob.get_balance()}")Minimize critical section duration: gather data outside, compute outside, and only write shared state inside. Long critical sections cause contention and kill scalability.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro