Is there multithreading in PHP?

When you start with multi-threading in PHP, you probably start by creating a Thread class and instantiating one for each of the tasks that you need doing. This is okay when you have just a few tasks, but you can quickly overload your server if you have a lot. Also, even if you scheduled the threads so that they didn't all run at once, it is highly inefficient to spawn a thread per task as there is overhead in creating and destroying the threads. It is much more efficient to re-use threads over and over again to complete these jobs. This is where a "pool" comes in and where one needs to separate "work" (or job/task) from "worker" (the thread).

Below is a script that defines a task class (MyTask) which gets instantiated a number of times with. Each time the task is given a list of numbers to perform calculations on ($inputs). We then instantiate a thread pool and hand the list of tasks to it to work on. The pool of threads will work until all the jobs have been completed, with each thread in the pool working on one job at a time. When all the tasks have been completed we get all the results out by asking the task objects for the results. We don't try to get the data back by going to the pool or the threads.

m_inputs = $inputs;
        $this->m_outputs = new Threaded(); // we will store the results in here.
    }


    public function run() 
    {
        foreach ($this->m_inputs as $input)
        {
            // casting the array to an array is not a mistake
            // but actually super important for this to work
            // https://github.com/krakjoe/pthreads/issues/813#issuecomment-361955116
            $this->m_outputs[] = (array)array(
                'property1' => $input * 2,
                'property2' => ($input + 2),
            );
        }
    }


    # Accessors
    public function getResults() { return $this->m_outputs; }
}



function main()
{
    $inputs = range(0,10000);
    $numInputsPerTask = 20;
    $inputGroups = array_chunk($inputs, $numInputsPerTask);
    $numCpus = 4; // I would nomrally dynamically fetch this and sometimes large (e.g. aws C5 instances)
    $numTasks = count($inputGroups);
    $numThreads = min($numTasks, $numCpus); // don't need to spawn more threads than tasks.
    $pool = new Pool($numThreads);
    $tasks = array(); // collection to hold all the tasks to get the results from afterwards.

    foreach ($inputGroups as $inputsForTask)
    {
        $task = new MyTask($inputsForTask);
        $tasks[] = $task;
        $pool->submit($task);
    }


    while ($pool->collect());

    # We could submit more stuff here, the Pool is still waiting for work to be submitted.

    $pool->shutdown();

    # All tasks should have been completed at this point. Get the results!
    $results = array();
    foreach ($tasks as $task)
    {
        $results[] = $task->getResults();
    }

    print "results: " . print_r($results, true);
}

main();

Getting the Answers Out

When I first started working with threads, I found it was easy enough to create them and get them to output messages, but I was confused as to how to retrieve the results by the main thread when the work had been done. This was because it hadn't clicked in my mind that the "job" stores the information about the parameters of the work and the result, not the thread. The thread just runs the job, with no clue about how it runs. You can think of the thread as a trained monkey that has been taught to turn a crank, and the jobs are containers with cranks on the outside that the monkey can access. The monkey has no clue whats going on inside the container when he turns the crank, but all the containers get their work done and have their result inside. One of the containers may have peeled potatoes when the crank was turned, whereas another might have been a manual generator that charged a battery.

Your PHP apps could really do with multi-threading capabilities for running tasks in parallel, but you know the PHP building process can be troublesome and time consuming — not only this, migrating your production server PHP to a new build…

Multithreading is a form of program execution, where a single process creates several threads, and they execute simultaneously. This tutorial will discuss multithreading in PHP and demonstrate how to achieve it.

Use the Parallel Parallel Concurrency Extension to Achieve Multithreading in PHP

Using the Parallel parallel concurrency extension, we can achieve multithreading in PHP.

The extension provides a interpreter thread parallel\Runtime. We can create an object from the parallel\Runtime() class and thus create a thread.

The class provides a method run() that schedules the tasks to run parallelly. We can pass Closure as the parameter to the run method.

The parameter is generally called

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
0, and we can also specify an array as the method’s second parameter. The content of the array is passed to the task.

There are some requirements before downloading the Parallel parallel concurrency extension. The PHP version should be 8.0, and Zend Thread Safe (ZTS) should be enabled.

The

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2 header is another requirement. We can download the extension from
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
3 as follows.

We can test the parallel execution of the program using the

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
4 loop.

For example, we can run a loop inside the run() method and another loop outside the method. In such conditions, the code execution will be parallel.

For example, create an object

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
6 of the parallel\Runtime class and then invoke the run() method with the object. Inside the run() method, write an anonymous function.

First, write a

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
4 loop to print the
for ($i=0; $i<5; $i++) {
 
 for ($j=0; $j<5; $j++) {
 $process[$j] = popen('message.php', 'r');
 }

 for ($j=0; $j<5; ++$j) {
 pclose($process[$j]);
 }
}
1 sign fifty times inside the function. Next, outside the run() method, write another
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
4 loop to print the
for ($i=0; $i<5; $i++) {
 
 for ($j=0; $j<5; $j++) {
 $process[$j] = popen('message.php', 'r');
 }

 for ($j=0; $j<5; ++$j) {
 pclose($process[$j]);
 }
}
4 sign fifty times.

As the loop inside the run() method runs in a separate thread, the loop outside the run() method will execute concurrently. As a result, the

for ($i=0; $i<5; $i++) {
 
 for ($j=0; $j<5; $j++) {
 $process[$j] = popen('message.php', 'r');
 }

 for ($j=0; $j<5; ++$j) {
 pclose($process[$j]);
 }
}
4 and
for ($i=0; $i<5; $i++) {
 
 for ($j=0; $j<5; $j++) {
 $process[$j] = popen('message.php', 'r');
 }

 for ($j=0; $j<5; ++$j) {
 pclose($process[$j]);
 }
}
1 sign are printed simultaneously, as shown in the output section below.

Therefore, we can use the parallel concurrency extension to achieve multithreading in PHP.

Example Code:

$rt = new \parallel\Runtime();

$rt->run(function(){
 for ($i = 0; $i < 50; $i++)
 echo "+";
});

for ($i = 0; $i < 50; $i++) {
 echo "-";
}

Output:

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Use the for ($i=0; $i<5; $i++) { for ($j=0; $j<5; $j++) { $process[$j] = popen('message.php', 'r'); } for ($j=0; $j<5; ++$j) { pclose($process[$j]); } } 9 Function to Achieve Multithreading in PHP

We can use the

for ($i=0; $i<5; $i++) {
 
 for ($j=0; $j<5; $j++) {
 $process[$j] = popen('message.php', 'r');
 }

 for ($j=0; $j<5; ++$j) {
 pclose($process[$j]);
 }
}
9 function to open parallel processes in PHP.

The function forks the process, and as a result, parallel processing is achieved. There is no sharing of the resources by the processes.

In this way, we can achieve multithreading in PHP. The

for ($i=0; $i<5; $i++) {
 
 for ($j=0; $j<5; $j++) {
 $process[$j] = popen('message.php', 'r');
 }

 for ($j=0; $j<5; ++$j) {
 pclose($process[$j]);
 }
}
9 function creates a pipe to the forked process.

We can loop over the

for ($i=0; $i<5; $i++) {
 
 for ($j=0; $j<5; $j++) {
 $process[$j] = popen('message.php', 'r');
 }

 for ($j=0; $j<5; ++$j) {
 pclose($process[$j]);
 }
}
9 function and create several processes to achieve multithreading. The
for ($i=0; $i<5; $i++) {
 
 for ($j=0; $j<5; $j++) {
 $process[$j] = popen('message.php', 'r');
 }

 for ($j=0; $j<5; ++$j) {
 pclose($process[$j]);
 }
}
9 function takes Parallel4 as the first parameter and Parallel5 as the second parameter.

The mode can be either Parallel6 or Parallel7.

For example, create a

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
4 loop that loops five times. Inside the loop, create another
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
4 loop that loops over five times.

Inside the child loop, create an array Parallel0 that stores the

for ($i=0; $i<5; $i++) {
 
 for ($j=0; $j<5; $j++) {
 $process[$j] = popen('message.php', 'r');
 }

 for ($j=0; $j<5; ++$j) {
 pclose($process[$j]);
 }
}
9 function. Set the PHP file Parallel2 and the Parallel6 mode as the first and second parameters.

Next, create another child loop and use the Parallel4 function to close the Parallel0.

Here, the five processes execute parallelly in the first child loop. The processes are terminated in the second child loop with the Parallel4 function.

Why is PHP not multithreaded?

A application uses threading if it requires parallelism. In other words by a single program ,we can process multiple unit of instructions parallaly. PHP do not give inbuilt multi-threading functionality, we need to add package/extension “pthreads” to our php.

How to make PHP multi thread?

You can use the pthreads extension in PHP <= 7.4 to enable multithreading in PHP. However, if you are using PHP > 7.4 then it would be great to use the parallel extension. Both of the given extensions can be downloaded from the “PECL” library of extensions.

How to use threading in PHP?

When the start method of a Thread is invoked, the run method code will be executed in separate Thread, in parallel. After the run method is executed the Thread will exit immediately, it will be joined with the creating Thread at the appropriate time.

Why is PHP single threaded?

The single threaded nature of PHP means that PHP doesn't have any built-in support for spawning new threads during script execution. However, this doesn't mean that you can't have two executions of the same script simultanously. In the most common setup, your website is served by Apache HTTPD.