class AsyncOperation extends \Thread {
public function __construct($arg){
$this->arg = $arg;
}
public function run(){
if($this->arg){
printf("Hello %s\n", $this->arg);
}
}
}
$thread = new AsyncOperation("World");
if($thread->start())
$thread->join();
?>运行以上代码出现 Hello World,说明pthreads扩展安装成功! <?php
namespace Home\Controller;
class test extends \Thread {
public $url;
public $result;
public function __construct($url) {
$this->url = $url;
}
public function run() {
if ($this->url) {
$this->result = model_http_curl_get($this->url);
}
}
}
function model_http_curl_get($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)');
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
for ($i = 0; $i < 10; $i++) {
$urls[] = 'http://www.baidu.com/s?wd='. rand(10000, 20000);
}
/* 多线程速度测试 */
$t = microtime(true);
foreach ($urls as $key=>$url) {
$workers[$key] = new test($url);
$workers[$key]->start();
}
foreach ($workers as $key=>$worker) {
while($workers[$key]->isRunning()) {
usleep(100);
}
if ($workers[$key]->join()) {
dump($workers[$key]->result);
}
}
$e = microtime(true);
echo "多线程耗时:".($e-$t)."秒<br>";
/* 单线程速度测试 */
$t = microtime(true);
foreach ($urls as $key=>$url) {
dump(model_http_curl_get($url));
}
$e = microtime(true);
echo "For循环耗时:".($e-$t)."秒<br>"; 测试结果如下:ThinkPHP 是一个免费开源的,快速、简单的面向对象的 轻量级PHP开发框架 ,创立于2006年初,遵循Apache2开源协议发布,是为了敏捷WEB应用开发和简化企业应用开发而诞生的。ThinkPHP从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,也注重易用性。并且拥有众多的原创功能和特性,在社区团队的积极参与下,在易用性、扩展性和性能方面不断优化和改进,已经成长为国内最领先和最具影响力的WEB应用开发框架,众多的典型案例确保可以稳定用于商业以及门户级的开发。