Is it possible to implement the multi-threading model in PHP, whether to actually implement it or just simulate it. Previously, it was suggested to force the operating system to load another instance of the PHP executable and handle other concurrent processes.
The problem with this is that when the PHP code completes execution, the PHP instance still resides in memory because it cannot be terminated from PHP. So you can imagine what will happen if you simulate multiple threads. So I'm still looking for a way to efficiently perform or simulate multi-threading in PHP. Any ideas?
Yes, you can use pthreads for multi-threading in PHP.
According to the PHP documentation:
pthreads is an object-oriented API that provides all the tools needed for multithreading in PHP. PHP applications can create, read, write, execute, and synchronize threads, worker threads, and threaded objects.
Warning:
The pthreads extension cannot be used in a web server environment. Therefore, multithreading in PHP should be limited to CLI-based applications.
#!/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); } } } // 创建一个数组 $stack = array(); // 启动多线程 foreach ( range("A", "D") as $i ) { $stack[] = new AsyncOperation($i); } // 启动所有线程 foreach ( $stack as $t ) { $t->start(); } ?>
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)) { /* * 如果请求大量数据,你可能想要使用 fsockopen 和 read,并在读取之间使用 usleep */ $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)); /* 开始同步 */ 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); }
The above is the detailed content of How Can I Implement Multithreading in PHP?. For more information, please follow other related articles on the PHP Chinese website!