{
    "slug": "mutex",
    "term": "Mutex & Locking",
    "category": "concurrency",
    "difficulty": "intermediate",
    "short": "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.",
    "long": "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.",
    "aliases": [],
    "tags": [
        "concurrency",
        "mutex",
        "locking",
        "redis"
    ],
    "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."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "race_condition",
        "deadlock",
        "semaphore",
        "atomic_operations"
    ],
    "prerequisites": [
        "race_condition"
    ],
    "refs": [
        "https://redis.io/docs/latest/develop/use/patterns/distributed-locks/"
    ],
    "bad_code": "$fp = fopen('lock.txt', 'c');\nflock($fp, LOCK_EX);\ndoWork(); // Exception here leaves lock held forever!\nflock($fp, LOCK_UN);\nfclose($fp);",
    "good_code": "// Always release in finally:\n$fp = fopen('lock.txt', 'c');\ntry {\n    flock($fp, LOCK_EX);\n    doWork();\n} finally {\n    flock($fp, LOCK_UN);\n    fclose($fp);\n}\n\n// Distributed mutex via Redis:\n$acquired = $redis->set('lock:job', 1, ['NX', 'EX' => 30]);\nif (!$acquired) return; // Another process holds it\ntry { doWork(); } finally { $redis->del('lock:job'); }",
    "quick_fix": "Always release locks in finally blocks. Use Redis SET NX EX for distributed locks. Set timeouts on locks to prevent indefinite holds.",
    "severity": "high",
    "effort": "medium",
    "created": "2026-03-23",
    "updated": "2026-03-23",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/mutex",
        "html_url": "https://codeclaritylab.com/glossary/mutex",
        "json_url": "https://codeclaritylab.com/glossary/mutex.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Mutex & Locking](https://codeclaritylab.com/glossary/mutex) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/mutex"
            }
        }
    }
}