巧妙解決PHP無法實(shí)現(xiàn)多線程的問題
有沒有辦法在PHP中實(shí)現(xiàn)多線程呢?假設(shè)你正在寫一個(gè)基于多臺(tái)服務(wù)器的PHP應(yīng)用,理想的情況時(shí)同時(shí)向多臺(tái)服務(wù)器發(fā)送請(qǐng)求,而不是一臺(tái)接一臺(tái)??梢詫?shí)現(xiàn)嗎?當(dāng)有人想要實(shí)現(xiàn)并發(fā)功能時(shí),他們通常會(huì)想到用fork或者spawn threads,但是當(dāng)他們發(fā)現(xiàn)PHP不支持多線程的時(shí)候,大概會(huì)轉(zhuǎn)換思路去用一些不夠好的語言,比如Perl。
51CTO推薦閱讀:優(yōu)秀的PHP開發(fā)者是怎樣煉成的?
其實(shí)的是大多數(shù)情況下,你大可不必使用fork或者線程,并且你會(huì)得到比用fork或thread更好的性能。假設(shè)你要建立一個(gè)服務(wù)來檢查正在運(yùn)行的n臺(tái)服務(wù)器,以確定他們還在正常運(yùn)轉(zhuǎn)。你可能會(huì)寫下面這樣的代碼:
- $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);
 - ?>
 
它運(yùn)行的很好,但是在fsockopen()分析完hostname并且建立一個(gè)成功的連接(或者延時(shí)$timeout秒)之前,擴(kuò)充這段代碼來管理大量服務(wù)器將耗費(fèi)很長(zhǎng)時(shí)間。
因此我們必須放棄這段代碼;我們可以建立異步連接-不需要等待fsockopen返回連接狀態(tài)。PHP仍然需要解析hostname(所以直接使用ip更加明智),不過將在打開一個(gè)連接之后立刻返回,繼而我們就可以連接下一臺(tái)服務(wù)器。
有兩種方法可以實(shí)現(xiàn);PHP5中可以使用新增的stream_socket_client()函數(shù)直接替換掉fsocketopen()。PHP5之前的版本,你需要自己動(dòng)手,用sockets擴(kuò)展解決問題。下面是PHP5中的解決方法:
- $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()調(diào)用系統(tǒng)的select(2)函數(shù)來工 作:前面三個(gè)參數(shù)是你要使用的streams的數(shù)組;你可以對(duì)其讀取,寫入和獲取異常(分別針對(duì)三個(gè)參數(shù))。stream_select()可以通過設(shè) 置$timeout(秒)參數(shù)來等待事件發(fā)生-事件發(fā)生時(shí),相應(yīng)的sockets數(shù)據(jù)將寫入你傳入的參數(shù)。
下面是PHP4.1.0之后版本的實(shí)現(xiàn),如果你已經(jīng)在編譯PHP時(shí)包含了sockets(ext/sockets)支持,你可以使用根上面類似的代 碼,只是需要將上面的streams/filesystem函數(shù)的功能用ext/sockets函數(shù)實(shí)現(xiàn)。主要的不同在于我們用下面的函數(shù)代替 stream_socket_client()來建立連接:
- // 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;
 - }
 - ?>
 
現(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
【編輯推薦】















 
 
 



 
 
 
 