windows下安裝php真正的多線程擴展pthreads教程

擴展地址:http://docs.php.net/manual/zh/book.pthreads.php

注意事項
php5.3或以上,且爲線程安全版本。apache和php使用的編譯器必須一致。
經過phpinfo()查看Thread Safety爲enabled則爲線程安全版。
經過phpinfo()查看Compiler項能夠知道使用的編譯器。本人的爲:MSVC9 (Visual C++ 2008)。


本人使用環境
32位windows xp sp3,wampserver2.2d(php5.3.10-vc9 + apache2.2.21-vc9)。


1、下載pthreads擴展
下載地址:http://windows.php.net/downloads/pecl/releases/pthreads
根據本人環境,我下載的是pthreads-2.0.8-5.3-ts-vc9-x86。
2.0.8表明pthreads的版本。
5.3表明php的版本。
ts表示php要線程安全版本的。
vc9表示php要Visual C++ 2008編譯器編譯的。
x86則表示32位的


2、安裝pthreads擴展
複製php_pthreads.dll 到目錄 bin\php\ext\ 下面。(本人路徑D:\wamp\bin\php\php5.3.10\ext)
複製pthreadVC2.dll 到目錄 bin\php\ 下面。(本人路徑D:\wamp\bin\php\php5.3.10)
複製pthreadVC2.dll 到目錄 C:\windows\system32 下面。
打開php配置文件php.ini。在後面加上extension=php_pthreads.dll
提示!Windows系統須要將 pthreadVC2.dll 所在路徑加入到 PATH 環境變量中。個人電腦--->鼠標右鍵--->屬性--->高級--->環境變量--->系統變量--->找到名稱爲Path的--->編輯--->在變量值最後面加上pthreadVC2.dll的完整路徑(本人的爲C:\WINDOWS\system32\pthreadVC2.dll)。


3、測試pthreads擴展php

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擴展安裝成功! html

附上一個Thinkphp3.2.2簡單例子thinkphp

<?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>";  

測試結果以下:
多線程耗時:2.8371710777282714844秒
For循環耗時:10.941586017608642578秒apache

原文出自:http://www.thinkphp.cn/topic/22676.htmlwindows

相關文章
相關標籤/搜索