Last active
October 23, 2015 09:52
-
-
Save forthxu/b5b7969eeab8541499c7 to your computer and use it in GitHub Desktop.
php thread example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| //example 使用多线程处理任务 | |
| // http://netkiller.github.io/journal/thread.php.html 比较全部的php多线程学习 | |
| class vote extends Thread { | |
| public $res = ''; | |
| public $url = array(); | |
| public $name = ''; | |
| public $runing = false; | |
| public function __construct($name) { | |
| $this->res = '暂无,第一次运行.'; | |
| $this->param = 0;//任务参数,如果为空说明线程等待任务 | |
| $this->preparam = 0;//上次任务参数 | |
| $this->name = $name;//线程名 | |
| $this->runing = true;//控制线程 | |
| } | |
| public function run() { | |
| //$this->runing可以控制线程结束 | |
| while ($this->runing) { | |
| if ($this->param != 0) { | |
| $nt = rand(1, 10); | |
| echo "线程[{$this->name}]收到任务参数::{$this->param},需要{$nt}秒处理数据.\n"; | |
| $this->res = rand(100, 999); | |
| sleep($nt);//执行过程所费时间 | |
| $this->preparam = $this->param; | |
| $this->param = ''; | |
| } else { | |
| echo "线程[{$this->name}]等待任务..\n"; | |
| sleep(1); | |
| } | |
| } | |
| } | |
| } | |
| //这里创建线程池. | |
| $pool[] = new vote('a'); | |
| $pool[] = new vote('b'); | |
| $pool[] = new vote('c'); | |
| //启动所有线程,使其处于工作状态 | |
| foreach ($pool as $w) { | |
| $w->start(); | |
| } | |
| //派发任务给线程 | |
| for ($i = 1; $i < 10; $i++) { | |
| //任务参数 | |
| $worker_content = rand(10, 99); | |
| //循环派发任务 | |
| while (true) { | |
| foreach ($pool as $worker) { | |
| //参数为空则说明线程空闲 | |
| if ($worker->param=='') { | |
| $worker->param = $worker_content; | |
| echo "任务【{$i}】[{$worker->name}]线程空闲,放入参数{$worker_content},上次参数[{$worker->preparam}]结果[{$worker->res}].\n"; | |
| break 2;//派发任务成功,进行下一个任务 | |
| } | |
| } | |
| //如果所有线程都繁忙时等待一秒钟 | |
| sleep(1); | |
| } | |
| } | |
| echo "所有线程派发完毕,等待执行完成.\n"; | |
| //等待所有线程运行结束 | |
| while (count($pool)) { | |
| //遍历检查线程组运行结束 | |
| foreach ($pool as $key => $threads) { | |
| if ($worker->param=='') { | |
| echo "[{$threads->name}]线程空闲,上次参数[{$threads->preparam}]结果[{$threads->res}].\n"; | |
| echo "[{$threads->name}]线程运行完成,退出.\n"; | |
| //设置结束标志 | |
| $threads->runing = false; | |
| unset($pool[$key]); | |
| } | |
| } | |
| echo "等待中...\n"; | |
| sleep(1); | |
| } | |
| echo "所有线程执行完毕.\n"; | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment