0
0
Operating-systemsConceptBeginner · 3 min read

What is Critical Section: Definition and Examples in OS

A critical section is a part of a program where shared resources are accessed and must not be used by more than one thread or process at the same time. It ensures safe access by preventing conflicts and data corruption in concurrent programming.
⚙️

How It Works

A critical section is like a single-lane bridge on a busy road. Only one car can cross at a time to avoid crashes. Similarly, in a program, when multiple threads want to use the same resource (like a file or variable), the critical section ensures only one thread uses it at once.

This is done by using locks or other synchronization tools. When a thread enters the critical section, it locks the resource. Other threads must wait until the lock is released before entering. This prevents errors like two threads changing data at the same time, which can cause wrong results or crashes.

💻

Example

This example shows two threads trying to increase the same number. Without a critical section, the final result can be wrong. Using a lock ensures the number is updated safely.

python
import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        with lock:  # Critical section starts
            counter += 1  # Only one thread can do this at a time

thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=increment)

thread1.start()
thread2.start()

thread1.join()
thread2.join()

print(f"Final counter value: {counter}")
Output
Final counter value: 200000
🎯

When to Use

Use critical sections whenever multiple threads or processes share data or resources that can be changed. This includes updating counters, writing to files, or accessing shared memory. Without critical sections, programs can behave unpredictably or crash.

For example, in a banking app, when two users try to withdraw money from the same account at the same time, a critical section ensures the balance updates correctly without losing any transaction.

Key Points

  • A critical section protects shared resources from simultaneous access.
  • It uses locks or synchronization to allow only one thread at a time.
  • Helps prevent data corruption and race conditions.
  • Essential in multi-threaded or multi-process programs.

Key Takeaways

A critical section ensures only one thread accesses shared data at a time to avoid conflicts.
Use locks or synchronization tools to protect critical sections in concurrent programs.
Without critical sections, data corruption and unpredictable behavior can occur.
Critical sections are vital in any program where multiple threads or processes share resources.