Multi-threading is possible in php
Yes you can do multi-threading in PHP with pthreads.
Of PHP documentation:
pthreads is an object-oriented API that provides all the tools needed for multi-threading in PHP. PHP applications can create, read, write, run and synchronize with Threads, Workers and Threaded objects.
Warning : The pthreads extension cannot be used in a web server environment. PHP threading should therefore remain for CLI-based applications only.
<?php
class OperacaoAssincrona extends Thread {
public function __construct($arg) {
$this->arg = $arg;
}
public function run() {
if ($this->arg) {
$sleep = mt_rand(1, 10);
printf('%s: %s -start -sleeps %d' . "\n", date("g:i:sa"), $this->arg, $sleep);
sleep($sleep);
printf('%s: %s -finish' . "\n", date("g:i:sa"), $this->arg);
}
}
}
// Criar um array
$stack = array();
//Inicializando multiplas Thread
foreach ( range("A", "D") as $i ) {
$stack[] = new OperacaoAssincrona($i);
}
// iniciar a Threads
foreach ( $stack as $t ) {
$t->start();
}
?>
First execution
12:00:06pm: A -start -sleeps 5
12:00:06pm: B -start -sleeps 3
12:00:06pm: C -start -sleeps 10
12:00:06pm: D -start -sleeps 2
12:00:08pm: D -finish
12:00:09pm: B -finish
12:00:11pm: A -finish
12:00:16pm: C -finish
Second Option
12:01:36pm: A -start -sleeps 6
12:01:36pm: B -start -sleeps 1
12:01:36pm: C -start -sleeps 2
12:01:36pm: D -start -sleeps 1
12:01:37pm: B -finish
12:01:37pm: D -finish
12:01:38pm: C -finish
12:01:42pm: A -finish
This is a model of how to use Multi-threading.
But a very good Pattern designer is Rxphp I think it’s worth taking a look.
Response reference:
How can one use multi threading in PHP Applications
if the data volume is large. Isn’t it better to work them out of the request and notify the user when their processing is completed? An example is facebook when you send a video, it releases the user and when the video is just processed it sends a notification.
– Hiago Souza
I could create an API and batch process as well, but the main question is still about the use/existence of multithreading.
– Darlei Fernando Zillmer
@Darleifernandozillmer found an article that can help you https://stackoverflow.com/questions/70855/how-can-one-use-multi-threading-in-php-applications. I hope there’s a good answer and on a pattern maybe Rxphp can help: https://github.com/ReactiveX/RxPHP
– Ricardo Lucas
I came to find this question and I’m testing something around pthreads now, but I’ll take a look at Rxphp as well
– Darlei Fernando Zillmer
Take a look at Parallel (php.net,packagist). He has more community support.
– Arthu Vinicius