PHP Multi Threading Extension Getting Started


To start with multi-threading, you would need the pthreads-ext for php, which can be installed by

$ pecl install pthreads

and adding the entry to php.ini.

A simple example:

// NOTE: Code uses PHP7 semantics.
class MyThread extends Thread {
     * @var string
     * Variable to contain the message to be displayed.
    private $message;
    public function __construct(string $message) {
        // Set the message value for this particular instance.
        $this->message = $message;

    // The operations performed in this function is executed in the other thread.
    public function run() {
        echo $this->message;

// Instantiate MyThread
$myThread = new MyThread("Hello from an another thread!");
// Start the thread. Also it is always a good practice to join the thread explicitly.
// Thread::start() is used to initiate the thread,
// and Thread::join() causes the context to wait for the thread to finish executing