PHP Pthread multithreaded Operations

Source: Internet
Author: User

<?PHPclassVoteextendsThread { Public $res= ' ';  Public $url=Array();  Public $name= ' ';  Public $runing=false;  Public $LC=false;  Public function__construct ($name) {        $this->res = ' Temporarily no, first run. '; $this->param = 0; $this->lurl = 0; $this->name =$name; $this->runing =true; $this-&GT;LC =false; }     Public functionrun () { while($this-runing) {            if($this->param! = 0) {                $nt=Rand(1, 10); Echo"Thread [{$this->name}] received task parameter:: {$this->param}, requires {$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}] Wait for the task. \ n "; }            Sleep(1); }    }}//this creates a thread pool.$pool[] =NewVote (' a ');$pool[] =NewVote (' B ');$pool[] =NewVote (' C ');//start all threads so that they are in a working stateforeach($pool  as $w) {    $w-start ();}//dispatch a task to a thread for($i= 1;$i< 10;$i++) {    $worker _content=Rand(10, 99);  while(true) {        foreach($pool  as $worker) {            //null argument indicates thread is idle            if($worker->param== ") {                $worker->param =$worker _content; Echo"[{$worker->name}] Thread is idle, put parameter {$worker _content}, last parameter [{$worker->lurl}] result [{$worker->res}].\n ";  Break2; }        }        Sleep(1); }}Echo"All threads are dispatched and wait for execution to complete. \ n";//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";

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.