Course contentsShow
← Computer Science
Lesson 1282 of 2,87230. Process SynchronizationFree lesson

Critical Section Protection with Locks

Using locks to wrap critical sections, ensuring only one thread executes the protected code at a time.

Critical Section Protection with Locks

What you'll learn: How to use locks to wrap critical sections so only one thread at a time can execute the protected code.

The Core Idea

Now that you understand lock semantics (acquire and release), let's see how locks actually protect critical sections in practice. The pattern is simple: place an acquire() call before the critical section and a release() call after it. This creates a protective wrapper that enforces mutual exclusion.

Think of it like a single-occupancy restroom with a lock on the door. Before entering (the critical section), you lock the door (acquire()). You do your business inside. When you're done, you unlock the door (release()). If someone else tries to enter while you're inside, they must wait until you unlock and leave.

How It Works

When a thread reaches acquire():

  • If the lock is available (unlocked), the thread takes it and enters the critical section
  • If the lock is held by another thread, this thread waits (blocks) until the lock becomes available

When a thread calls release():

  • The lock becomes available again
  • One waiting thread (if any) can now acquire it and proceed

The Protection Pattern

acquire(lock)
    // Critical section - shared data access
    // Only ONE thread executes this at a time
release(lock)

This pattern guarantees that even if multiple threads execute this code, the critical section runs atomically from each thread's perspective—no interleaving of critical section code between threads.

Key Takeaway: By wrapping critical sections with acquire() and release(), locks enforce mutual exclusion, preventing race conditions and ensuring only one thread accesses shared data at a time.