国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

PHP多線程的實現方法詳解

2024-05-04 21:48:32
字體:
來源:轉載
供稿:網友

多線程是java中一個很不錯的東西,很多朋友說在php中不可以使用PHP多線程了,其實那是錯誤的說法PHP多線程實現方法和fsockopen函數有關,下面我們來介紹具體實現程序代碼,有需要了解的同學可參考.

當有人想要實現并發功能時,他們通常會想到用fork或者spawn threads,但是當他們發現php不支持多線程的時候,大概會轉換思路去用一些不夠好的語言,比如perl.

其實的是大多數情況下,你大可不必使用 fork 或者線程,并且你會得到比用 fork 或 thread 更好的性能.

假設你要建立一個服務來檢查正在運行的n臺服務器,以確定他們還在正常運轉,你可能會寫下面這樣的代碼:

  1. <?php 
  2. $hosts = array("host1.sample.com""host2.sample.com""host3.sample.com"); 
  3. $timeout = 15; 
  4. $status = array(); 
  5. foreach ($hosts as $host) { 
  6.  $errno = 0; 
  7.  $errstr = ""
  8.  $s = fsockopen($host, 80, $errno$errstr$timeout); 
  9.  if ($s) { 
  10.   $status[$host] = "Connectedn"
  11.   fwrite($s"HEAD / HTTP/1.0rnHost: $hostrnrn"); 
  12.   do { 
  13.    $data = fread($s, 8192); 
  14.    if (strlen($data) == 0) { 
  15.    break
  16.    } 
  17.    $status[$host] .= $data
  18.   } while (true); 
  19.   fclose($s); 
  20.  } else { 
  21.   $status[$host] = "Connection failed: $errno $errstrn"
  22.  } 
  23. print_r($status); 
  24. ?> 

它運行的很好,但是在fsockopen()分析完hostname并且建立一個成功的連接,或者延時$timeout秒之前,擴充這段代碼來管理大量服務器將耗費很長時間.

因此我們必須放棄這段代碼,我們可以建立異步連接-不需要等待fsockopen返回連接狀態。PHP仍然需要解析hostname,所以直接使用ip更加明智,不過將在打開一個連接之后立刻返回,繼而我們就可以連接下一臺服務器.

有兩種方法可以實現,PHP5中可以使用新增的stream_socket_client()函數直接替換掉fsocketopen(),PHP5之前的版本,你需要自己動手,用sockets擴展解決問題.

下面是PHP5中的解決方法,代碼如下:

  1. <?php 
  2. $hosts = array("host1.sample.com""host2.sample.com""host3.sample.com"); 
  3. $timeout = 15; 
  4. $status = array(); 
  5. $sockets = array(); 
  6. /* Initiate connections to all the hosts simultaneously */ 
  7. foreach ($hosts as $id => $host) { 
  8.  $s = stream_socket_client(" 
  9. $host:80", $errno$errstr$timeout
  10.   STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT); 
  11.  if ($s) { 
  12.   $sockets[$id] = $s
  13.   $status[$id] = "in progress"
  14.  } else { 
  15.   $status[$id] = "failed, $errno $errstr"
  16.  } 
  17. /* Now, wait for the results to come back in */ 
  18. while (count($sockets)) { 
  19.  $read = $write = $sockets
  20.  /* This is the magic function - explained below */ 
  21.  $n = stream_select($read$write$e = null, $timeout); 
  22.  if ($n > 0) { 
  23.   /* readable sockets either have data for us, or are failed 
  24.    * connection attempts */ 
  25.   foreach ($read as $r) { 
  26.       $id = array_search($r$sockets); 
  27.       $data = fread($r, 8192); 
  28.       if (strlen($data) == 0) { 
  29.    if ($status[$id] == "in progress") { 
  30.     $status[$id] = "failed to connect"
  31.    } 
  32.    fclose($r); 
  33.    unset($sockets[$id]); 
  34.       } else { 
  35.    $status[$id] .= $data
  36.       } 
  37.   } 
  38.   /* writeable sockets can accept an HTTP request */ 
  39.   foreach ($write as $w) { 
  40.    $id = array_search($w$sockets); 
  41.    fwrite($w"HEAD / HTTP/1.0rnHost: " 
  42.     . $hosts[$id] .  "rnrn"); 
  43.    $status[$id] = "waiting for response"
  44.   } 
  45.  } else { 
  46.   /* timed out waiting; assume that all hosts associated 
  47.    * with $sockets are faulty */ 
  48.   foreach ($sockets as $id => $s) { 
  49.    $status[$id] = "timed out " . $status[$id]; 
  50.   } 
  51.   break
  52.  } 
  53. foreach ($hosts as $id => $host) { 
  54.  echo "Host: $hostn"
  55.  echo "Status: " . $status[$id] . "nn"
  56. }  
  57. ?> 

我們用stream_select()等待sockets打開的連接事件,stream_select()調用系統的select(2)函數來工作,前面三個參數是你要使用的streams的數組,你可以對其讀取,寫入和獲取異常,分別針對三個參數,stream_select()可以通過設置$timeout(秒)參數來等待事件發生-事件發生時,相應的sockets數據將寫入你傳入的參數.

下面是PHP4.1.0之后版本的實現,如果你已經在編譯PHP時包含了sockets(ext/sockets)支持,你可以使用根上面類似的代碼,只是需要將上面的streams/filesystem函數的功能用ext/sockets函數實現,主要的不同在于我們用下面的函數代替stream_socket_client()來建立連接,代碼如下:

  1. <?php 
  2. // This value is correct for Linux, other systems have other values 
  3. define('EINPROGRESS', 115); 
  4. function non_blocking_connect($host$port, &$errno, &$errstr$timeout) { 
  5.  $ip = gethostbyname($host); 
  6.  $s = socket_create(AF_INET, SOCK_STREAM, 0); 
  7.  if (socket_set_nonblock($s)) { 
  8.   $r = @socket_connect($s$ip$port); 
  9.   if ($r || socket_last_error() == EINPROGRESS) { 
  10.    $errno = EINPROGRESS; 
  11.    return $s
  12.   } 
  13.  } 
  14.  $errno = socket_last_error($s); 
  15.  $errstr = socket_strerror($errno); 
  16.  socket_close($s); 
  17.  return false; 
  18. ?> 

現在用socket_select()替換掉stream_select(),用socket_read()替換掉fread(),用socket_write()替換掉fwrite(),用socket_close()替換掉fclose()就可以執行腳本了.

PHP5的先進之處在于,你可以用stream_select()處理幾乎所有的stream-例如你可以通過include STDIN用它接收鍵盤輸入并保存進數組,你還可以接收通過proc_open()打開的管道中的數據.

下面來分享一個PHP多線程類,代碼如下:

  1. * @title:      PHP多線程類(Thread) 
  2. * @version:    1.0 
  3. * @author:     phper.org.cn < web@phper.org.cn > 
  4. * @published:  2010-11-2 
  5. *  
  6. * PHP多線程應用示例: 
  7. *  require_once 'thread.class.php'
  8. *  $thread = new thread(); 
  9. *  $thread->addthread('action_log','a'); 
  10. *  $thread->addthread('action_log','b'); 
  11. *  $thread->addthread('action_log','c'); 
  12. *  $thread->runthread(); 
  13. *   
  14. *  function action_log($info) { 
  15. *      $log = 'log/' . microtime() . '.log'
  16. *      $txt = $info . "rnrn" . 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "rn"
  17. *      $fp = fopen($log'w'); 
  18. *      fwrite($fp$txt); 
  19. *      fclose($fp); 
  20. *  } 
  21. */ 
  22. lass thread { 
  23.  
  24.    var $hooks = array(); 
  25.    var $args = array(); 
  26.  
  27.    function thread() { 
  28.    } 
  29.  
  30.    function addthread($func
  31.    { 
  32.        $args = array_slice(func_get_args(), 1); 
  33.        $this->hooks[] = $func
  34.        $this->args[] = $args
  35.        return true; 
  36.    } 
  37.  
  38.    function runthread() 
  39.    { 
  40.        if(isset($_GET['flag'])) 
  41.        { 
  42.            $flag = intval($_GET['flag']); 
  43.        } 
  44.        if($flag || $flag === 0) 
  45.        { 
  46.            call_user_func_array($this->hooks[$flag], $this->args[$flag]); 
  47.        } 
  48.        else 
  49.        { 
  50.            for($i = 0, $size = count($this->hooks); $i < $size$i++) 
  51.            { 
  52.                $fp=fsockopen($_SERVER['HTTP_HOST'],$_SERVER['SERVER_PORT']);//開源代碼Vevb.com 
  53.                if($fp
  54.                { 
  55.                    $out = "GET {$_SERVER['PHP_SELF']}?flag=$i HTTP/1.1rn"
  56.                    $out .= "Host: {$_SERVER['HTTP_HOST']}rn"
  57.                    $out .= "Connection: Closernrn"
  58.                    fputs($fp,$out); 
  59.                    fclose($fp); 
  60.                } 
  61.            } 
  62.        } 
  63.    } 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 开原市| 双辽市| 汾西县| 蕉岭县| 张家界市| 广水市| 丰城市| 满城县| 屏东市| 嘉兴市| 濮阳县| 尉氏县| 金湖县| 阆中市| 麦盖提县| 阳春市| 郯城县| 晋江市| 乌恰县| 山东省| 布尔津县| 拜泉县| 耒阳市| 井陉县| 剑河县| 德江县| 阿合奇县| 韩城市| 大竹县| 东安县| 淮北市| 乌兰察布市| 平乡县| 九龙县| 忻州市| 岳阳县| 清远市| 绥滨县| 襄汾县| 和平区| 沧源|