首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >会话开始与php中的usleep冲突

会话开始与php中的usleep冲突
EN

Stack Overflow用户
提问于 2012-07-23 19:00:33
回答 1查看 308关注 0票数 0

我想写一个聊天系统。我用过ajax,php和commet porotocol。

一切正常,但是session有一个问题:当session在脚本的顶部启动时,一切都出错(我的脚本无法理解,并且有一个新的msg,所以我必须等待睡眠时间结束)

这是我的php文件的一个简单版本:

代码语言:javascript
复制
   $filename  = dirname(__FILE__).'/data.txt';

// store new message in the file
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
if ($msg != '')
{
  file_put_contents($filename,$msg);
  die();
}
// infinite loop until the data file is not modified
$lastmodif    = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) // check if the data file has been modified
{
  usleep(10000); // sleep 10ms to unload the CPU
  clearstatcache();
  $currentmodif = filemtime($filename);
}

// return a json array
$response = array();
$response['msg']       = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-23 19:58:53

这是因为会话处于锁定状态,避免这种情况的唯一方法是在执行usleep命令之前调用session_write_close()

基本上,如果一个脚本使用会话,则对于使用相同web浏览器的同一客户端,其他脚本不能同时运行,直到第一个脚本完成或调用session_write_close()。这是因为PHP使用了锁定,看到会话文件被锁定,将等待它再次可用,然后再运行脚本。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11611217

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档