下面我們來介紹具體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);
- ?>
新聞熱點
疑難解答