Is multi threading possible in php?

Many of you are beginning to notice pthreads, unfortunately the people writing about pthreads and concurrency in PHP are not well equipped to provide advice, to tackle this I have decided to reddit about some misconceptions I have come across ...

  1. PHP is not thread safe, there are lots of extensions that will give your application cooties.

In reality this hasn't been true for a very very long time. TSRM has been discussed and explained in other threads on reddit, the fact is that PHP does support multi threaded execution of the interpreter and has done for 13 years, a lot of effort is made to ensure that at least internal and bundled functionality doesn't do anything stupid when executing in a ZTS environment. pthreads creates contexts for execution just as the Apache Module does using a worker mpm.

2) pthreads is old fashioned

The pecl extension pthreads and Posix Threads are not nearly the same thing, posix threads are brilliant but complex, pthreads is just brilliant ;)

pthreads does not mean Posix Threads when we talk about php, it means php threads, but php threads is a crappy name ... pthreads !== Posix Threads, no where near it ...

3) pthreads does not include everything you need to execute safely

Simply wrong; as it says in the documentation, it includes all you need to write truly multi-threaded applications in PHP. Operations on the object scope are implicitly atomic, safety is ensured, all the time ...

4) pthreads unsafely shares memory among contexts in order to provide concurrent functionality

Again, wrong. PHP is a shared nothing architecture and the Zend MM prohibits contexts from writing each other during execution, that's what makes things like Apache 2 module work in multi-threaded mode without strangeness at the interpreter level. The fact is that even if you pass data to a function that in turn uses that data in a non-reentrant way, it will make absolutely no difference because the data you pass is always a copy; pthreads utilizes copy on read and copy on write to maintain the shared nothing architecture and keep sane the executor.

5) pthreads is beta and should be avoided at all costs

I marked pthreads beta because of what it is. Lots of people are using pthreads in production and I've been asked multiple times to change the status of the extension such that network managers will allow devs to install it.

One day, pthreads will be marked stable, since all the kinks are nearly worked out that should hopefully be in the next few releases. Until then, beta doesn't mean unusable, it means that you may experience an error or the unexpected, those that have read documentation and examples should have less problems, and everyone should report every bug they find either on bugs.php.net or github.

Multi-threading in PHP sounds like some sort of voodoo, for so long it's been something that was either impossible in the minds of php programmers, or a bad idea to try and emulate. pthreads doesn't emulate anything, it leverages bundled functionality and the object API to provide true userland multi-threading.

I encourage anyone looking at pthreads to read every single example included, and take good note of the documentation, it will be beneficial to scan the documentation through before you start. I'm aware PHP programmers aren't used to having to read the instructions, but, we are pushing the envelope, there isn't a million ways to do everything as there normally is in PHP, there is a single, correct way to do things, and they are pretty well documented by now.

Lastly, happy phping :)

  1. HowTo
  2. PHP Howtos
  3. Achieve Multithreading in PHP

Created: December-18, 2021

  1. Use the Parallel Parallel Concurrency Extension to Achieve Multithreading in PHP
  2. Use the popen() Function to Achieve Multithreading in PHP

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 task, 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 <pthread.h> header is another requirement. We can download the extension from pecl as follows.

pecl install parallel

We can test the parallel execution of the program using the for 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 $rt 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 for loop to print the + sign fifty times inside the function. Next, outside the run() method, write another for loop to print the - 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 - and + 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 popen() Function to Achieve Multithreading in PHP

We can use the popen() 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 popen() function creates a pipe to the forked process.

We can loop over the popen() function and create several processes to achieve multithreading. The popen() function takes command as the first parameter and mode as the second parameter.

The mode can be either r or w.

For example, create a for loop that loops five times. Inside the loop, create another for loop that loops over five times.

Inside the child loop, create an array $process that stores the popen() function. Set the PHP file message.php and the r mode as the first and second parameters.

Next, create another child loop and use the pclose() function to close the $process.

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

This is how we can achieve multithreading using the popen() function in PHP.

Example Code:

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]);
 }
}

Can PHP be multi threading?

PHP applications, undoubtedly work effectively with multithreading capabilities. Multithreading is something similar to multitasking, but it enables to process multiple jobs at one time, rather than on multiple processes.

Is PHP single threaded or multi threaded?

PHP as a language has zero support for multithreading and as such is single-threaded.

Can you have multiple threads?

Multithreading is a model of program execution that allows for multiple threads to be created within a process, executing independently but concurrently sharing process resources. Depending on the hardware, threads can run fully parallel if they are distributed to their own CPU core.

Is laravel support multithreading?

So instead of a single process carrying out the jobs, you will have multiple queue worker processes running the jobs in different queues. Each queue will be a single threaded process (unless you compile php for multithreading and then utilize it). It's up to you to split up the queues accordingly.