轉:http://blog.iyi.cn/start/
問題:
有沒有辦法在php中實現多線程呢?
假設你正在寫一個基於多台伺服器的php應用,理想的情況時同時向多台伺服器發送請求,而不是一台接一台。
可以實現嗎?
回答:
當有人想要實現並發功能時,他們通常會想到用fork或者spawn threads,但是當他們發現php不支援多線程的時候,大概會轉換思路去用一些不夠好的語言,比如perl。
其實的是大多數情況下,你大可不必使用fork或者線程,並且你會得到比用fork或thread更好的效能。
假設你要建立一個服務來檢查正在啟動並執行n台伺服器,以確定他們還在正常運轉。你可能會寫下面這樣的代碼:
<?php
$hosts = array("host1.sample.com", "host2.sample.com", "host3.sample.com");
$timeout = 15;
$status = array();
foreach ($hosts as $host) {
$errno = 0;
$errstr = "";
$s = fsockopen($host, 80, $errno, $errstr, $timeout);
if ($s) {
$status[$host] = "Connectedn";
fwrite($s, "HEAD / HTTP/1.0rnHost: $hostrnrn");
do {
$data = fread($s, 8192);
if (strlen($data) == 0) {
break;
}
$status[$host] .= $data;
} while (true);
fclose($s);
} else {
$status[$host] = "Connection failed: $errno $errstrn";
}
}
print_r($status);
?>
它啟動並執行很好,但是在fsockopen()分析完hostname並且建立一個成功的串連(或者延時$timeout秒)之前,擴充這段代碼來管 理大量伺服器將耗費很長時間。
因此我們必須放棄這段代碼;我們可以建立非同步串連-不需要等待fsockopen返回串連狀態。PHP仍然需要解析hostname(所以直接使用ip更 加明智),不過將在開啟一個串連之後立刻返回,繼而我們就可以串連下一台伺服器。
有兩種方法可以實現;PHP5中可以使用新增的stream_socket_client()函數直接替換掉fsocketopen()。PHP5之前的 版本,你需要自己動手,用sockets擴充解決問題。
下面是PHP5中的解決方案:
<?php
$hosts = array("host1.sample.com", "host2.sample.com", "host3.sample.com");
$timeout = 15;
$status = array();
$sockets = array();
/* Initiate connections to all the hosts simultaneously */
foreach ($hosts as $id => $host) {
$s = stream_socket_client("$host:80", $errno, $errstr, $timeout,
STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
if ($s) {
$sockets[$id] = $s;
$status[$id] = "in progress";
} else {
$status[$id] = "failed, $errno $errstr";
}
}
/* Now, wait for the results to come back in */
while (count($sockets)) {
$read = $write = $sockets;
/* This is the magic function - explained below */
$n = stream_select($read, $write, $e = null, $timeout);
if ($n > 0) {
/* readable sockets either have data for us, or are failed
* connection attempts */
foreach ($read as $r) {
$id = array_search($r, $sockets);
$data = fread($r, 8192);
if (strlen($data) == 0) {
if ($status[$id] == "in progress") {
$status[$id] = "failed to connect";
}
fclose($r);
unset($sockets[$id]);
} else {
$status[$id] .= $data;
}
}
/* writeable sockets can accept an HTTP request */
foreach ($write as $w) {
$id = array_search($w, $sockets);
fwrite($w, "HEAD / HTTP/1.0rnHost: "
. $hosts[$id] . "rnrn");
$status[$id] = "waiting for response";
}
} else {
/* timed out waiting; assume that all hosts associated
* with $sockets are faulty */
foreach ($sockets as $id => $s) {
$status[$id] = "timed out " . $status[$id];
}
break;
}
}
foreach ($hosts as $id => $host) {
echo "Host: $hostn";
echo "Status: " . $status[$id] . "nn";
}
?>
我們用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()來建立串連:
<?php
// This value is correct for Linux, other systems have other values
define('EINPROGRESS', 115);
function non_blocking_connect($host, $port, &$errno, &$errstr, $timeout) {
$ip = gethostbyname($host);
$s = socket_create(AF_INET, SOCK_STREAM, 0);
if (socket_set_nonblock($s)) {
$r = @socket_connect($s, $ip, $port);
if ($r || socket_last_error() == EINPROGRESS) {
$errno = EINPROGRESS;
return $s;
}
}
$errno = socket_last_error($s);
$errstr = socket_strerror($errno);
socket_close($s);
return false;
}
?>
現在用socket_select()替換掉stream_select(),用socket_read()替換掉fread(),用 socket_write()替換掉fwrite(),用socket_close()替換掉fclose()就可以執行指令碼了!
PHP5的先進之處在於,你可以用stream_select()處理幾乎所有的stream-例如你可以通過include STDIN用它接收鍵盤輸入並儲存進數組,你還可以接收通過proc_open()開啟的管道中的資料。
如果你想讓PHP4.3.x自身擁有處理streams的功能,我已經為你準備了一個讓fsockopen可以非同步工作的patch。不贊成使用該補丁,
該補丁不會出現在官方發布的PHP版本中,我在補丁中附帶了stream_socket_client()函數的實現,通過它,你可以讓你的指令碼相容
PHP5。
附件:
documentation for stream_select()
documentation for socket_select()
patch for PHP 4.3.2 and script to emulate stream_socket_client(). (might work with later 4.3.x versions).
------------------------------------
經測試,確實為多線程,弄了整個下午,終於弄好了~~~
$request = array("http://10.1.30.218/test/server.php","http://10.1.30.28/server.php
");
foreach($request as $r) {
$temp = parse_url($r);
$scheme[] = $temp['scheme'];
$hosts[] = $temp['host'];
$paths[] = isset($temp['path']) ? $temp['path'] : "" ;
}
//$hosts = array("www.bit.edu.cn
");
$timeout = 5;
$status = array();
$sockets = array();
// Initiate connections to all the hosts simultaneously
foreach ($hosts as $id => $host) {
$s = stream_socket_client("$host:80", $errno, $errstr, $timeout, STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
if ($s) {
$sockets[$id] = $s;
$status[$id] = "in progress";
} else {
$status[$id] = "failed, $errno $errstr";
}
}
//print_r($sockets);print_r($status);
//*
// Now, wait for the results to come back in
while (count($sockets)) {
$read = $write = $sockets;
// This is the magic function - explained below
$ret = stream_select($read, $write, $e = null, $timeout);
if ($ret > 0) {
// readable sockets either have data for us, or are failed connection attempts
foreach ($read as $r) {
$id = array_search($r, $sockets);
$data = fread($r, 8192);
if (strlen($data) == 0) {
if ($status[$id] == "in progress") {
$status[$id] = "failed to connect";
}
fclose($r);
unset($sockets[$id]);
} else {
if ($status[$id] == "in progress") {
$status[$id] = $data;
} else {
$status[$id] .= $data;
}
}
}
// writeable sockets can accept an HTTP request
foreach ($write as $w) {
$id = array_search($w, $sockets);
//fwrite($w, "HEAD / HTTP/1.0/r/nHost: " . $hosts[$id] . "/r/n/r/n");
fwrite($w, "GET /".$paths[$id]." HTTP/1.0/r/nHost: " . $hosts[$id] . "/r/n/r/n");
//$status[$id] = "waiting for response";
}
} else {
// timed out waiting; assume that all hosts associated with $sockets are faulty
foreach ($sockets as $id => $s) {
$status[$id] = "timed out/r/n/r/n" . $status[$id];
}
break;
}
}
foreach ($hosts as $id => $host) {
echo "Host: $host/n";
echo '<pre>'.$status[$id].'</pre>';
/*
$pos = strpos($status[$id],"/r/n/r/n");
$content[$id] = substr($status[$id],$pos);
$status[$id] = substr($status[$id],0,$pos);
//echo "Status: " . $status[$id] . "/n/n";
echo $content[$id] . "/n/n" ;
*/
}