Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one use multi threading in PHP applications

Is there a realistic way of implementing a multi-threaded model in PHP whether truly, or just simulating it. Some time back it was suggested that you could force the operating system to load another instance of the PHP executable and handle other simultaneous processes.

The problem with this is that when the PHP code finished executing the PHP instance remains in memory because there is no way to kill it from within PHP. So if you are simulating several threads you can imagine whats going to happen. So I am still looking for a way multi-threading can be done or simulated effectively from within PHP. Any ideas?

like image 631
Steve Obbayi Avatar asked Sep 16 '08 09:09

Steve Obbayi


People also ask

Can we use multithreading in PHP?

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.

What are some applications of using multiple threads?

Multiple threads of execution are used to load content, display animations, play a video, and so on. Another example of a multithreaded program that we are all familiar with is a word processor.

Can we use multithreading in Web applications?

Thanks to great advancements lately, developers can now implement multithreading in their apps. Using Web Workers, tasks can be run in its isolated threads. Data gets serialized/deserialized before/after being sent between the main thread and a worker.

How can we achieve multi threading?

Step1: Implement a run() method provided by a Runnable interface. Step2: Instantiate a Thread object using the following constructor. Step3: Once the Thread object is created, the thread can be started by calling start() method, which executes a call to run( ) method.


2 Answers

Multi-threading is possible in php

Yes you can do multi-threading in PHP with pthreads

From the PHP documentation:

pthreads is an object-orientated API that provides all of the tools needed for multi-threading in PHP. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects.

Warning: The pthreads extension cannot be used in a web server environment. Threading in PHP should therefore remain to CLI-based applications only.

Simple Test

#!/usr/bin/php <?php class AsyncOperation 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);         }     } }  // Create a array $stack = array();  //Initiate Multiple Thread foreach ( range("A", "D") as $i ) {     $stack[] = new AsyncOperation($i); }  // Start The Threads foreach ( $stack as $t ) {     $t->start(); }  ?> 

First Run

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 Run

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 

Real World Example

error_reporting(E_ALL); class AsyncWebRequest extends Thread {     public $url;     public $data;      public function __construct($url) {         $this->url = $url;     }      public function run() {         if (($url = $this->url)) {             /*              * If a large amount of data is being requested, you might want to              * fsockopen and read using usleep in between reads              */             $this->data = file_get_contents($url);         } else             printf("Thread #%lu was not provided a URL\n", $this->getThreadId());     } }  $t = microtime(true); $g = new AsyncWebRequest(sprintf("http://www.google.com/?q=%s", rand() * 10)); /* starting synchronization */ if ($g->start()) {     printf("Request took %f seconds to start ", microtime(true) - $t);     while ( $g->isRunning() ) {         echo ".";         usleep(100);     }     if ($g->join()) {         printf(" and %f seconds to finish receiving %d bytes\n", microtime(true) - $t, strlen($g->data));     } else         printf(" and %f seconds to finish, request failed\n", microtime(true) - $t); } 
like image 198
Baba Avatar answered Oct 07 '22 03:10

Baba


why don't you use popen?

for ($i=0; $i<10; $i++) {     // open ten processes     for ($j = 0; $j < 10; $j++) {         $pipe[$j] = popen('script2.php', 'w');     }      // wait for them to finish     for ($j = 0; $j < 10; ++$j) {         pclose($pipe[$j]);     } } 
like image 31
masterb Avatar answered Oct 07 '22 03:10

masterb