一、下载pthreads扩展
下载地址:http://windows.php.net/downloads/pecl/releases/pthreads
我下载的是php_pthreads-2.0.9-5.5-ts-vc11-x64.zip //5.5对应的是php版本,64位是系统位数
二、安装pthreads扩展
复制php_pthreads.dll 到目录 bin\php\ext\ 下面。(D:\wamp\bin\php\php5.5.12\ext)
复制pthreadVC2.dll 到目录 bin\php\ 下面。(D:\wamp\bin\php\php5.5.12)
复制pthreadVC2.dll 到目录 C:\windows\system32 下面。
打开php配置文件php.ini。在后面加上extension=php_pthreads.dll
提示!Windows系统需要将 pthreadVC2.dll 所在路径加入到 PATH 环境变量中。
我的电脑--->鼠标右键--->属性--->高级--->环境变量--->系统变量--->找到名称为Path的--->编辑--->在变量值最后面加上pthreadVC2.dll的完整路径(C:\WINDOWS\system32\pthreadVC2.dll)。
访问phpinfo.php 可以看到 pthreads扩展
测试pthreads扩展
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扩展安装成功!
例子:
header("Content-type:text/html;charset=utf-8");
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()) {
var_dump($workers[$key]->result);
}
}
$e = microtime(true);
echo "多线程耗时:".($e-$t)."秒<br>";
/ 单线程速度测试 /
$t = microtime(true);
foreach ($urls as $key=>$url) {
var_dump(model_http_curl_get($url));
}
$e = microtime(true);
echo "For循环耗时:".($e-$t)."秒<br>";
已有 0 条评论