This article mainly introduces how PHP uses Pthread to implement multi-threaded operations. it analyzes the creation and use of php multithreading in the form of a complete example, for more information about how to use Pthread in PHP, see the following example. We will share this with you for your reference. The details are as follows:
<? Php class vote extends Thread {public $ res = ''; public $ url = array (); public $ name =''; public $ runing = false; public $ lc = false; public function _ construct ($ name) {$ this-> res = 'None, run for the first time. '; $ this-> param = 0; $ this-> lurl = 0; $ this-> name = $ name; $ this-> runing = true; $ this-> lc = false;} public function run () {while ($ this-> runing) {if ($ this-> param! = 0) {$ nt = rand (1, 10); echo "thread [{$ this-> name}] receives the task parameter: {$ this-> param }, it takes {$ 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}] waiting 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 to make them in the working state foreach ($ pool as $ w) {$ w-> start ();} // dispatch a task to the thread for ($ I = 1; $ I <10; $ I ++) {$ worker_content = rand (10, 99); while (true) {foreach ($ pool as $ worker) {// if the parameter is null, the thread is idle if ($ worker-> param = '') {$ worker-> param = $ worker_content; echo "[{$ worker-> name}] thread idle, put the parameter {$ worker_content }, result of last parameter [{$ worker-> lurl}] [{$ worker-> res}]. \ n "; break 2 ;}} sleep (1) ;}} echo" all threads are distributed, waiting for execution to complete. \ n "; // wait for all threads to finish running while (count ($ pool) {// traverse and check the Thread Group running to end foreach ($ pool as $ key => $ threads) {if ($ worker-> param = '') {echo" [{$ threads-> name}] the thread is idle, result of last parameter [{$ threads-> lurl}] [{$ threads-> res}]. \ n "; echo" [{$ threads-> name}] the thread is running completely and exits. \ n "; // set the end Flag $ threads-> runing = false; unset ($ pool [$ key]) ;}} echo" waiting... \ n "; sleep (1) ;}echo" all threads have been executed. \ n ";
I hope this article will help you with php programming.