{
    "slug": "php_fiber_internals",
    "term": "PHP Fibers — Internals & Scheduler Patterns",
    "category": "php",
    "difficulty": "advanced",
    "short": "How PHP Fibers work under the hood — stack allocation, suspension mechanics, and how to build a cooperative multitasking scheduler on top of the Fiber API introduced in PHP 8.1.",
    "long": "A PHP Fiber is a stackful coroutine — it gets its own call stack (unlike generators which resume from a single yield point). Internally, the Zend Engine allocates a separate C stack for each fiber (configurable via `fiber.stack_size` in php.ini, default 2MB) and saves/restores CPU registers and the stack pointer on suspend/resume. `Fiber::suspend($value)` saves the current stack frame, returns control to the caller, and passes `$value` out. `$fiber->resume($value)` restores the stack frame and passes `$value` back in as the return value of `Fiber::suspend()`. Unlike threads, fibers are cooperative — only one fiber runs at a time, switching only at explicit `Fiber::suspend()` calls, so no mutexes are needed for shared state. A scheduler is a loop that tracks pending fibers and resumes them when their awaited condition is met (I/O ready, timer elapsed). Libraries like ReactPHP and Revolt PHP use fibers to implement `async/await`-style concurrency on top of an event loop.",
    "aliases": [
        "fibers internals",
        "PHP coroutines",
        "stackful coroutines",
        "cooperative multitasking PHP"
    ],
    "tags": [
        "php",
        "fibers",
        "concurrency",
        "async",
        "scheduler",
        "php81"
    ],
    "misconception": "PHP Fibers enable true parallel execution — Fibers are cooperative, single-threaded concurrency. Only one fiber runs at a time; they interleave by voluntarily suspending, not by running on separate CPU cores. For true parallelism use `parallel` extension or separate processes.",
    "why_it_matters": "Fibers are the foundation of async PHP — frameworks like Revolt, ReactPHP 3+, and Amp v3 use them to write I/O-concurrent code that reads like synchronous PHP but suspends at I/O boundaries. Understanding fibers lets you debug async PHP code, tune stack size, and build lightweight schedulers for CLI tools.",
    "common_mistakes": [
        "Not handling exceptions thrown into a fiber — `$fiber->throw(new Exception)` resumes the fiber with an exception at the suspend point; uncaught, it propagates to the caller.",
        "Blocking inside a fiber (sleep(), PDO query without async driver) — blocks the entire PHP process, defeating the purpose of cooperative concurrency.",
        "Creating thousands of fibers simultaneously — each fiber allocates a full stack (default 2MB); 1000 fibers = 2GB RAM. Pool and reuse fibers for high-concurrency workloads.",
        "Calling `Fiber::suspend()` outside a fiber — throws a `FiberError`; always check `Fiber::getCurrent() !== null`."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "fibers",
        "fibers_revolt",
        "coroutines",
        "event_driven_concurrency",
        "async_processing",
        "generators"
    ],
    "prerequisites": [
        "fibers",
        "coroutines",
        "generators"
    ],
    "refs": [
        "https://www.php.net/manual/en/class.fiber.php",
        "https://wiki.php.net/rfc/fibers",
        "https://revolt.run"
    ],
    "bad_code": "// Blocking inside a fiber — defeats cooperative concurrency:\n$fiber = new Fiber(function(): void {\n    sleep(2);           // blocks entire process — no other fiber runs\n    $result = file_get_contents('https://example.com'); // blocking I/O\n    Fiber::suspend($result);\n});\n$fiber->start();",
    "good_code": "// Simple cooperative scheduler using Fibers + non-blocking I/O:\nclass Scheduler {\n    private array $fibers = [];\n\n    public function add(Fiber $fiber): void {\n        $this->fibers[] = $fiber;\n    }\n\n    public function run(): void {\n        while ($this->fibers) {\n            foreach ($this->fibers as $key => $fiber) {\n                if (!$fiber->isStarted()) $fiber->start();\n                elseif ($fiber->isSuspended()) $fiber->resume();\n\n                if ($fiber->isTerminated()) {\n                    unset($this->fibers[$key]);\n                }\n            }\n        }\n    }\n}\n\n$scheduler = new Scheduler();\n$scheduler->add(new Fiber(function(): void {\n    echo \"Task A: step 1\\n\";\n    Fiber::suspend(); // yield control\n    echo \"Task A: step 2\\n\";\n}));\n$scheduler->add(new Fiber(function(): void {\n    echo \"Task B: step 1\\n\";\n    Fiber::suspend();\n    echo \"Task B: step 2\\n\";\n}));\n$scheduler->run();\n// Output: Task A: step 1 / Task B: step 1 / Task A: step 2 / Task B: step 2",
    "example_note": "The scheduler round-robins between fibers — each runs until it suspends, then the next gets a turn, showing cooperative interleaving without threads.",
    "quick_fix": "Never call blocking functions (sleep, PDO, file_get_contents) inside a fiber — use non-blocking async equivalents from Revolt or ReactPHP",
    "severity": "medium",
    "effort": "high",
    "created": "2026-03-24",
    "updated": "2026-03-24",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/php_fiber_internals",
        "html_url": "https://codeclaritylab.com/glossary/php_fiber_internals",
        "json_url": "https://codeclaritylab.com/glossary/php_fiber_internals.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": "[PHP Fibers — Internals & Scheduler Patterns](https://codeclaritylab.com/glossary/php_fiber_internals) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/php_fiber_internals"
            }
        }
    }
}