The Parallel extension for PHP is a modern extension that enables true parallelism by allowing PHP code to execute multiple tasks concurrently in separate threads. Unlike traditional asynchronous programming, which relies on non-blocking I/O, the Parallel extension uses Runtime
objects to create and manage threads, providing a straightforward, object-oriented approach to multitasking.
First of all, let’s make sure you’ve got the extension enabled in PHP. You can install it by using pecl.
pecl install parallel
Verify that the extension is working and loaded by checking phpinfo()
on your environment. Once you have confirmed that it’s installed and running, we’ll dive into a basic example of running 3 threads and allowing the script to wait for the value.
<?php
use parallel\Runtime;
use parallel\Future;
// Define a function to run in parallel
function parallelTask($taskName) {
echo "$taskName is running on Thread ID: " . parallel\current()->getThreadId() . "\n";
sleep(2); // Simulating a task taking time to complete
return "$taskName completed";
}
// Create Runtime objects for each thread
$runtime1 = new Runtime();
$runtime2 = new Runtime();
$runtime3 = new Runtime();
// Start each task in its own thread
$future1 = $runtime1->run(function () {
return parallelTask('Task 1');
});
$future2 = $runtime2->run(function () {
return parallelTask('Task 2');
});
$future3 = $runtime3->run(function () {
return parallelTask('Task 3');
});
// Main script can continue doing other work here...
// Retrieve and print results of each task once they are done
echo $future1->value() . "\n"; // Waits for Task 1 to finish and gets its result
echo $future2->value() . "\n"; // Waits for Task 2 to finish and gets its result
echo $future3->value() . "\n"; // Waits for Task 3 to finish and gets its result
?>
As you can see above, we define 3 runtime objects and inside the ->run anonymous function we return the result of the parallelTask
, where we have passed in a unique string so that we know which thread is running/stopped.
The ->value()
method of the Runtime class waits for that specific task to finish before returning the value. This is a very nice solution if you have to do lots of processing or data analysis on different data and don’t want to wait for each one to finish.
The output of the above code should look something like:
Task 1 is running on Thread ID: 1
Task 2 is running on Thread ID: 2
Task 3 is running on Thread ID: 3
Task 1 completed
Task 2 completed
Task 3 completed
Add more Runtime objects and tasks and maybe pass in the amount of time to delay the function, and see which tasks finish in order (for a simulation)