0
0
PHPprogramming~30 mins

Fibers for concurrency in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Fibers for concurrency
📖 Scenario: You are building a simple PHP script that uses fibers to run two tasks concurrently. Fibers allow you to pause and resume code execution, which helps manage multiple tasks without waiting for each to finish before starting the next.
🎯 Goal: Create two fibers that each count numbers with a pause, then run them concurrently by switching between them. Finally, print the combined output showing the interleaved counting.
📋 What You'll Learn
Create two fibers named fiber1 and fiber2 that each count from 1 to 3 with a pause between counts.
Create a variable output to store the combined counting results as a string.
Use a loop to switch between fiber1 and fiber2 until both finish.
Print the output string showing the interleaved counts.
💡 Why This Matters
🌍 Real World
Fibers help PHP programs handle multiple tasks at once without waiting for each to finish, useful in web servers or background jobs.
💼 Career
Understanding fibers prepares you for writing efficient, concurrent PHP code in modern applications and frameworks.
Progress0 / 4 steps
1
Create two fibers for counting
Create two fibers called fiber1 and fiber2. Each fiber should count from 1 to 3. Inside each fiber, use a for loop with variable i from 1 to 3, and after each count, use Fiber::suspend() to pause the fiber.
PHP
Need a hint?

Use new Fiber(function() { ... }) to create each fiber. Inside, use a for loop and call Fiber::suspend() with a string showing the fiber name and count.

2
Create an output variable
Create a variable called output and set it to an empty string "". This will store the combined results from both fibers.
PHP
Need a hint?

Just write $output = ""; to start with an empty string.

3
Run fibers concurrently and collect output
Use a while loop that runs as long as either fiber1 or fiber2 is not terminated. Inside the loop, check if fiber1 is not terminated, then resume it and append the returned string to output. Do the same for fiber2. Use $fiber1->isTerminated() and $fiber2->isTerminated() to check if fibers finished.
PHP
Need a hint?

Use while with the condition checking both fibers. Inside, resume each fiber if not terminated and add the returned string to output.

4
Print the combined output
Write a print statement to display the output variable.
PHP
Need a hint?

Use print($output); to show the combined counting results.