PHP Multithreading  screenshot

PHP Multithreading

PHP Multithreading

PHP continues to evolve even after having been conceived in the dawn of the web as we know it. At the time of laying down its core principles and functionality, personal computers weren’t nearly as powerful as some modern mobile devices. Server machines were also quite on the slow side, and multiple core processors were still unheard of.

However, with today’s technology, everything today has a multi-core processor. Phones, computers, laptops, tablets and devices of all sorts and configurations can now make good use of multi-threading. So why shouldn’t your server stack use it too? Well, now that threading has been introduced to PHP, it can (and totally should).

Multi-threading allows you to use up your machine’s resources intelligently. Instead of running everything in the same old top-to-bottom continuous execution, you can run tasks in parallel. What you are looking for is pthreads - The API that allows you to implement most sorts of multi-threading in your PHP code.

For installation of the pthreads extension, refer to the official guide here

A simple code example:

<?php
class PThread extends Thread {
    $id = ""; //ThreadID
    public function __construct($idThread) {
        $this->id = $idThread;
    }
    public function run() {
        if ($this->id) {
            $sleep = mt_rand(1, 10);
            printf('Thread: %s  has started, sleeping for %d' . "\n", $this->id, $sleep);
            sleep($sleep);
            printf('Thread: %s  has finished' . "\n", $this->id);
        }
    }
}
// Creating the pool of threads(stored as array)
$poolArr = array();
//Initiating the threads
foreach (range("0", "3") as $i) {
    $poolArr[] = new PThread($i);
}
//Start each Thread
foreach ($stackArr as $t) {
    $t->start();
}
//Wait all thread to finish
foreach (range(0, 3) as $i) {
    $poolArr[$i]->join();
}
//Next... other sentences with all threads finished.
 
?>

Which in turn will output:

<?php
//The output will show...
//Thread 0 has started, sleeping for 6
//Thread 1 has started, sleeping for 4
//Thread 2 has started, sleeping for 10
//Thread 3 has started, sleeping for 3
//Thread 3 has finished
//Thread 1 has finished
//Thread 0 has finished
//Thread 2 has finished
 
?>

You can see that you can declare your own thread by extending the “Thread” class which pthreads offers you. From then on it’s a pretty straightforward matter of constructing your class.

In the loop where we fill our stack array ($stackArr), we also initialize the threads by passing an argument to their “run” function, which in turn is used as an identifier for the thread.

In the end, they’re all started concurrently (start() is a function that belongs to the extended “Thread” class), their given instructions are executed and their output is shown when each finishes.

Although the times and order of finishing will vary in each run, this should show you that now you do not have to wait until a thread has finished executing another one. Running pieces of code in such a manner is applicable to lots and lots of cases in the real world. Let’s suppose you want to read a large amount of data but you don’t want to hold your whole script up while it’s being read. You can leave the code that handles the reading in a thread and execute a different set of instructions for monitoring it or anything else you may need in parallel.