Codacoda
Back to Academy

concurrency

Mutex & Locks

A mutex (mutual exclusion) is a synchronization primitive that ensures only one thread or process can access a shared resource at a time. When a thread acquires a lock, all other threads must wait until the lock is released before proceeding. Mutexes prevent data corruption caused by concurrent writes to shared state. They are the most fundamental building block of thread-safe programming.

Use Cases

  • Protecting shared counters or accumulators from concurrent modification
  • Ensuring only one thread writes to a file or database connection at a time
  • Guarding critical sections in multi-threaded server request handlers
  • Synchronizing access to in-memory caches shared across workers

Visualization

INITIALMutex LockCritical Sectioncounter = 0Thread 1idleThread 2idle
Speed:1x
Two threads need access to a shared critical section protected by a mutex lock.Step 1 / 7

Implementation

Output

Click "Run Code" to see output...