PHP中实现非阻塞模式
程序非阻塞模式,这里也可以理解成并发。而并发又暂且可以分为网络请求并发
和本地并发
。
先说一下网络请求并发
理论描述
假设有一个client,程序逻辑是要请求三个不同的server,处理各自的响应。传统模型当然是顺序执行,先发送第一个请求,等待收到响应数据后再发送第二个请求,以此类推。就像是单核CPU,一次只能处理一件事,其他事情被暂时阻塞。而并发模式可以让三个server同时处理各自请求,这就可以使大量时间复用。
画个图更好说明问题:
前者为阻塞模式,忽略请求响应等时间,总耗时为700ms;而后者非阻塞模式,由于三个请求可以同时得到处理,总耗时只有300ms。
代码实现
<?php
echo "Program starts at ". date('h:i:s') . ".\n";
$timeout = 3;
$sockets = array(); //socket句柄数组
//一次发起多个请求
$delay = 0;
while ($delay++ < 3)
{
$sh = stream_socket_client("localhost:80", $errno, $errstr, $timeout,
STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
/* 这里需要稍微延迟一下,否则下面fwrite中的socket句柄不一定能真正使用
这里应该是PHP的一处bug,查了一下,官方bug早在08年就有人提交了
我的5.2.8中尚未解决,不知最新的5.3中是否修正
*/
usleep(10);
if ($sh) {
$sockets[] = $sh;
$http_header = "GET /test.php?n={$delay} HTTP/1.0\r\n";
$http_header .= "Host: localhost\r\n";
$http_header .= "Accept: */*\r\n";
$http_header .= "Accept-Charset: *\r\n";
$http_header .= "\r\n";
fwrite($sh, $http_header);
} else {
echo "Stream failed to open correctly.\n";
}
}
//非阻塞模式来接收响应
$result = array();
$read_block_size = 8192;
while (count($sockets))
{
$read = $sockets;
$n = stream_select($read, $w=null, $e=null, $timeout);
//if ($n > 0) //据说stream_select返回值不总是可信任的
if (count($read))
{
/* stream_select generally shuffles $read, so we need to
compute from which socket(s) we're reading. */
fo
相关文档:
function file_list($path) {
$handle = opendir($path);
if ($handle) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (is_dir($path."/".$file)) {
echo "<br /><br /><b> ......
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</ ......
原文链接:http://www.phpdo.net/index.php/20100411/56.html
在PHP中使用foreach函数可以遍历数组。Foreach仅能用于数组,语法如下:
Foreach(array as $value) statements
Foreach(array as $key=>$value) statement
第一种语法遍历数组时,每次循环时,当前单元的值被赋给$value,数组内部的指针向前 ......
<html>
<head>
<script type="text/javascript">
<!--
function confirmDelete()
{
return confirm("Are you sure you wish to delete this entry?");
}
//-->
</script>
</head>
<body>
<% $var1 = 2;%> ......