会话启动与php中的usleep冲突


Session start conflicting with usleep in php

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

一切都很好,但会话有一个问题:当会话在脚本顶部启动时,一切都出了问题(我的脚本无法忍受有一条新消息,所以我必须等待睡眠时间结束)

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

   $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();

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

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