• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

Multiple processes/threads access shared resources concurrently, leading to race conditions (incorrect results when operations interleave). We need a synchronization mechanism to coordinate access.

Core Idea

A semaphore is an integer variable with two atomic operations (wait/signal) used to control access to shared resources and prevent race conditions.

How It Works

  1. Semaphore has integer value (initialized to N = number of available resources)
  2. wait() (P operation): Decrement semaphore; if negative, block the process
  3. signal() (V operation): Increment semaphore; if was negative, wake up a blocked process
  4. Operations are atomic (cannot be interrupted mid-execution)
semaphore Process1 Process 1 Sem Semaphore S (value) Process1->Sem wait(S) Process2 Process 2 Process2->Sem wait(S) CS Critical Section Sem->CS enter if S>0 CS->Sem signal(S)

Key Properties

  • Atomic operations (wait/signal) prevent race conditions
  • Can be binary (0/1) for mutual exclusion
  • Can be counting (0..N) for resource pools
  • Used to solve producer-consumer, reader-writer problems

Connections

Edge Cases & Gotchas

  • Busy waiting in some implementations wastes CPU
  • Deadlock if processes wait for each other circularly
  • Priority inversion: high-priority process blocked by lower-priority holder