Mutex & Locking
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'); }
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
23 Mar 2026
Views
48
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 1
No pings yesterday
Amazonbot 13
Perplexity 10
Google 5
Unknown AI 4
SEMrush 3
ChatGPT 2
Ahrefs 2
Majestic 1
Also referenced
How they use it
crawler 38
pre-tracking 2
Related categories
⚡
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