自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

巧妙解決PHP無法實(shí)現(xiàn)多線程的問題

開發(fā) 后端
有沒有辦法在PHP中實(shí)現(xiàn)多線程呢?其實(shí)的是大多數(shù)情況下,你大可不必使用fork或者線程,并且你會得到比用fork或thread更好的性能。

有沒有辦法在PHP中實(shí)現(xiàn)多線程呢?假設(shè)你正在寫一個基于多臺服務(wù)器的PHP應(yīng)用,理想的情況時同時向多臺服務(wù)器發(fā)送請求,而不是一臺接一臺。可以實(shí)現(xiàn)嗎?當(dāng)有人想要實(shí)現(xiàn)并發(fā)功能時,他們通常會想到用fork或者spawn threads,但是當(dāng)他們發(fā)現(xiàn)PHP不支持多線程的時候,大概會轉(zhuǎn)換思路去用一些不夠好的語言,比如Perl。

51CTO推薦閱讀:優(yōu)秀的PHP開發(fā)者是怎樣煉成的?

其實(shí)的是大多數(shù)情況下,你大可不必使用fork或者線程,并且你會得到比用fork或thread更好的性能。假設(shè)你要建立一個服務(wù)來檢查正在運(yùn)行的n臺服務(wù)器,以確定他們還在正常運(yùn)轉(zhuǎn)。你可能會寫下面這樣的代碼:

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

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

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

有兩種方法可以實(shí)現(xiàn);PHP5中可以使用新增的stream_socket_client()函數(shù)直接替換掉fsocketopen()。PHP5之前的版本,你需要自己動手,用sockets擴(kuò)展解決問題。下面是PHP5中的解決方法:

  1. $hosts = array("host1.sample.com", "host2.sample.com", "host3.sample.com");  
  2. $timeout = 15;  
  3. $status = array();  
  4. $sockets = array();  
  5. /* Initiate connections to all the hosts simultaneously */  
  6. foreach ($hosts as $id => $host) {   
  7.         $s = stream_socket_client("$host:80", $errno, $errstr, $timeout,    
  8.              STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);   
  9.         if ($s) {    
  10.             $sockets[$id] = $s;    
  11.             $status[$id] = "in progress";   
  12.         }   
  13.         else {  $status[$id] = "failed, $errno $errstr";   
  14.         }  
  15. }  
  16. /* Now, wait for the results to come back in */  
  17.  
  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   * connection attempts */    
  24.           foreach ($read as $r) {        
  25.                    $id = array_search($r, $sockets);        
  26.                    $data = fread($r, 8192);        
  27.           if (strlen($data) == 0) {     
  28.                    if ($status[$id] == "in progress") {      
  29.                        $status[$id] = "failed to connect";     
  30.                    }     
  31.           fclose($r);     
  32.           unset($sockets[$id]);        
  33.            }   
  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. }   
  46. else {    
  47. /* timed out waiting; assume that all hosts associated   * with $sockets are faulty */    
  48. foreach ($sockets as $id => $s) {     
  49.          $status[$id] = "timed out "   
  50.          . $status[$id];    
  51.          }    
  52. break;   
  53.   }  
  54. }  
  55. foreach ($hosts as $id => $host) {   
  56.       echo "Host: $hostn"; echo "Status: "   
  57.       . $status[$id] . "nn";  
  58. }   
  59. ?> 

我們用stream_select()等待sockets打開的連接事件。stream_select()調(diào)用系統(tǒng)的select(2)函數(shù)來工 作:前面三個參數(shù)是你要使用的streams的數(shù)組;你可以對其讀取,寫入和獲取異常(分別針對三個參數(shù))。stream_select()可以通過設(shè) 置$timeout(秒)參數(shù)來等待事件發(fā)生-事件發(fā)生時,相應(yīng)的sockets數(shù)據(jù)將寫入你傳入的參數(shù)。

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

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

現(xiàn)在用socket_select()替換掉stream_select(),用socket_read()替換掉fread(),用socket_write()替換掉fwrite(),用socket_close()替換掉fclose()就可以執(zhí)行腳本了!
PHP5的先進(jìn)之處在于,你可以用stream_select()處理幾乎所有的stream。例如你可以通過include STDIN用它接收鍵盤輸入并保存進(jìn)數(shù)組,你還可以接收通過proc_open()打開的管道中的數(shù)據(jù)。

原文地址:http://blog.csdn.net/bluephper/archive/2010/01/13/5184861.aspx

【編輯推薦】

  1. PHP 5.0中多態(tài)性的實(shí)現(xiàn)方案淺析
  2. PHP 5.3閉包語法初探
  3. 探秘PHP 5的對象重載技術(shù)
  4. PHP 5.3中的命名空間:你用過了么? 
責(zé)任編輯:王曉東 來源: CSDN博客
相關(guān)推薦

2009-12-31 14:50:12

ADSL網(wǎng)絡(luò)無法解析

2010-01-05 16:09:37

交換機(jī)無法ping通

2009-01-15 09:49:00

網(wǎng)絡(luò)地址切換

2009-11-18 15:39:43

PHP函數(shù)

2023-08-02 07:39:07

多線程開發(fā)資源

2010-03-15 11:07:13

Python多線程

2024-04-08 10:09:37

TTLJava框架

2009-12-11 13:33:14

PHP無法修改head

2013-12-05 09:45:04

HadoopHadoop架構(gòu)圖

2010-03-16 17:00:02

Java多線程支持

2023-03-02 08:19:43

不加鎖程序實(shí)時性

2009-09-14 19:39:14

批量線程同步

2010-02-01 17:25:09

Python多線程

2010-08-03 09:41:14

GroupSQL Server

2015-04-17 10:31:11

PHP下載美女圖片實(shí)現(xiàn)代碼

2009-07-03 17:18:34

Servlet多線程

2010-03-15 18:11:38

Java多線程

2019-09-26 10:19:27

設(shè)計(jì)電腦Java

2010-09-30 15:10:12

Javascriptimg

2011-06-22 13:47:16

Java多線程
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號