The examples in this article describe the multithreaded operations that PHP implements with Pthread. Share to everyone for your reference, as follows:
<?phpclass vote extends Thread {public $res = '; Public $url = Array (); Public $name = '; Public $runing = false; Public $LC = false; Public function __construct ($name) {$this->res = ' temporarily none, first run. '; $this->param = 0; $this->lurl = 0; $this->name = $name; $this->runing = true; $this->LC = false; The public Function run () {$this->runing) {if ($this->param! = 0) {$nt = rand (1, 10); echo "Thread [{$this->name}] received the task parameter: {$this->param}, {$nt} seconds to process the data. \ n"; $this->res = rand (100, 999); Sleep ($NT); $this->lurl = $this->param; $this->param = "; } else {echo ' thread [{$this->name}] waits for the task: \ n "; } sleep (1); }}//Create a thread pool here. $pool [] = new vote (' a '), $pool [] = new vote (' B '), $pool [] = new vote (' C ');//start all threads so that they are in the working state of foreach ($pool as $w) {$w->start ();} Dispatch task to thread for ($i = 1; $i < $i + +) {$worker _content = rand (10, 99); while (true) { A foreach ($pool as $worker) {//parameter is NULL indicates that the thread is idle if ($worker->param== ") {$worker->param = $worker _co ntent; echo "[{$worker->name}] Thread is idle, put in parameter {$worker}, last parameter [{$worker->lurl}] result [{$worker->res}].\n]; Break 2; }} sleep (1); }}echo "All threads are dispatched, wait for execution to complete. \//wait for all threads to run end while (count ($pool)) {//Traverse check thread group run end foreach ($pool as $key = = $threads) { if ($worker->param== ") {echo" [{$threads->name}] Thread is idle, last parameter [{$threads->lurl}] result [{$threads->res}].\n]; echo "[{$threads->name}] thread run complete, exit. \ n"; Set End flag $threads->runing = false; Unset ($pool [$key]); }} echo "Waiting ... \ n"; Sleep (1);} echo "All threads have finished executing. \ n";
I hope this article is helpful to you in PHP programming.