← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Mutex & Locking

concurrency Intermediate

TL;DR

A mutex (mutual exclusion lock) ensures only one thread/process can access a critical section at a time — the fundamental primitive for preventing race conditions.

Explanation

Mutex: binary lock — locked or unlocked. Only the holder can unlock it. Critical section: code protected by the mutex. In PHP: flock() for file-based mutex, Redis SET NX EX for distributed mutex, database advisory locks (GET_LOCK in MySQL). Key properties: atomicity of lock/unlock, single-owner, blocking (waits) vs non-blocking (returns false if unavailable). Distributed systems need distributed locks (Redis Redlock, ZooKeeper, DB advisory locks) since file locks only work within one server. Deadlock risk: never hold mutex A while acquiring mutex B (or maintain consistent order). Release in finally to ensure unlock even on exception.

Common Misconception

flock() provides a distributed lock across multiple servers — flock() is per-server only. Multiple PHP-FPM servers need Redis or DB-based distributed locking.

Why It Matters

Mutexes are the foundation of concurrent programming correctness — without them, any shared mutable state is a potential race condition.

Common Mistakes

  • Not releasing mutex in a finally block — lock held forever on exception.
  • Using flock() as a distributed lock across multiple servers — doesn't work.
  • Holding a mutex too long — reduces concurrency, increases contention.

Code Examples

✗ Vulnerable
$fp = fopen('lock.txt', 'c');
flock($fp, LOCK_EX);
doWork(); // Exception here leaves lock held forever!
flock($fp, LOCK_UN);
fclose($fp);
✓ Fixed
// Always release in finally:
$fp = fopen('lock.txt', 'c');
try {
    flock($fp, LOCK_EX);
    doWork();
} finally {
    flock($fp, LOCK_UN);
    fclose($fp);
}

// Distributed mutex via Redis:
$acquired = $redis->set('lock:job', 1, ['NX', 'EX' => 30]);
if (!$acquired) return; // Another process holds it
try { doWork(); } finally { $redis->del('lock:job'); }

Added 23 Mar 2026
Views 48
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 1 ping W 0 pings T 0 pings F 2 pings S 0 pings S 0 pings M 1 ping T 0 pings W 0 pings T 1 ping F 2 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 0 pings F 1 ping S
No pings yesterday
Amazonbot 13 Perplexity 10 Google 5 Unknown AI 4 SEMrush 3 ChatGPT 2 Ahrefs 2 Majestic 1
crawler 38 pre-tracking 2
DEV INTEL Tools & Severity
🟠 High ⚙ Fix effort: Medium
⚡ Quick Fix
Always release locks in finally blocks. Use Redis SET NX EX for distributed locks. Set timeouts on locks to prevent indefinite holds.
📦 Applies To
web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
flock\(|LOCK_EX
Auto-detectable: ✗ No
⚠ Related Problems
🤖 AI Agent
Confidence: Medium False Positives: Medium ✗ Manual fix Fix: Medium Context: Function Tests: Update
CWE-662

✓ schema.org compliant