进程锁定问题分析研究

 更新时间:2016年11月25日 16:29  点击:1311


<?php
/**
* 进行写锁定的测试
* 打开线程1
*/
require("file_lock.php");
$lock = new File_Lock(dirname(dirname(__FILE__)) . "/FileLock.lock");
/** 单个线程锁定的速度 1s 钟 3万次。 **/
/** 两个线程写,两万的数据 大概要 7s 钟*/
/** 一个线程写,一万的数据 大概要 3.9s 钟,居然两个文件同时写,要快一点*/
/** 不进行锁定,一个进程 写大概要 2.8s 钟,加锁是有代价的。 */
/** 不进行锁定,两个进程 分布不是很均匀,而且大多数都冲突 */
$lock->writeLock();
$lock->increment();
$lock->unlock();
while ($lock->get() < 2) {
usleep(1000);
}
sleep(1);
echo "begin to runing n";
$t1 = microtime(true);
for ($i = 0; $i < 10000; $i++)
{
$lock->writeLock();
$lock->increment(1);
$lock->unlock();
}
$t2 = microtime(true) - $t1;
echo $t2;
?>


<?php
class File_Lock
{
private $name;
private $handle;
private $mode;
function __construct($filename, $mode = 'a+b')
{
global $php_errormsg;
$this->name = $filename;
$path = dirname($this->name);
if ($path == '.' || !is_dir($path)) {
global $config_file_lock_path;
$this->name = str_replace(array("/", "\"), array("_", "_"), $this->name);
if ($config_file_lock_path == null) {
$this->name = dirname(__FILE__) . "/lock/" . $this->name;
} else {
$this->name = $config_file_lock_path . "/" . $this->name;
}
}
$this->mode = $mode;
$this->handle = @fopen($this->name, $mode);
if ($this->handle == false) {
throw new Exception($php_errormsg);
}
}
public function close()
{
if ($this->handle !== null ) {
@fclose($this->handle);
$this->handle = null;
}
}
public function __destruct()
{
$this->close();
}
public function lock($lockType, $nonBlockingLock = false)
{
if ($nonBlockingLock) {
return flock($this->handle, $lockType | LOCK_NB);
} else {
return flock($this->handle, $lockType);
}
}
public function readLock()
{
return $this->lock(LOCK_SH);
}
public function writeLock($wait = 0.1)
{
$startTime = microtime(true);
$canWrite = false;
do {
$canWrite = flock($this->handle, LOCK_EX);
if(!$canWrite) {
usleep(rand(10, 1000));
}
} while ((!$canWrite) && ((microtime(true) - $startTime) < $wait));
}
/**
* if you want't to log the number under multi-thread system,
* please open the lock, use a+ mod. then fopen the file will not
* destroy the data.
*
* this function increment a delt value , and save to the file.
*
* @param int $delt
* @return int
*/
public function increment($delt = 1)
{
$n = $this->get();
$n += $delt;
$this->set($n);
return $n;
}
public function get()
{
fseek($this->handle, 0);
return (int)fgets($this->handle);
}
public function set($value)
{
ftruncate($this->handle, 0);
return fwrite($this->handle, (string)$value);
}
public function unlock()
{
if ($this->handle !== null ) {
return flock($this->handle, LOCK_UN);
} else {
return true;
}
}
}
?>

 


class Memcache_Queue
{
private $memcache;
private $name;
private $prefix;
function __construct($maxSize, $name, $memcache, $prefix = "__memcache_queue__")
{
if ($memcache == null) {
throw new Exception("memcache object is null, new the object first.");
}
$this->memcache = $memcache;
$this->name = $name;
$this->prefix = $prefix;
$this->maxSize = $maxSize;
$this->front = 0;
$this->real = 0;
$this->size = 0;
}
function __get($name)
{
return $this->get($name);
}
function __set($name, $value)
{
$this->add($name, $value);
return $this;
}
function isEmpty()
{
return $this->size == 0;
}
function isFull()
{
return $this->size == $this->maxSize;
}
function enQueue($data)
{
if ($this->isFull()) {
throw new Exception("Queue is Full");
}
$this->increment("size");
$this->set($this->real, $data);
$this->set("real", ($this->real + 1) % $this->maxSize);
return $this;
}
function deQueue()
{
if ($this->isEmpty()) {
throw new Exception("Queue is Empty");
}
$this->decrement("size");
$this->delete($this->front);
$this->set("front", ($this->front + 1) % $this->maxSize);
return $this;
}
function getTop()
{
return $this->get($this->front);
}
function getAll()
{
return $this->getPage();
}
function getPage($offset = 0, $limit = 0)
{
if ($this->isEmpty() || $this->size < $offset) {
return null;
}
$keys[] = $this->getKeyByPos(($this->front + $offset) % $this->maxSize);
$num = 1;
for ($pos = ($this->front + $offset + 1) % $this->maxSize; $pos != $this->real; $pos = ($pos + 1) % $this->maxSize)
{
$keys[] = $this->getKeyByPos($pos);
$num++;
if ($limit > 0 && $limit == $num) {
break;
}
}
return array_values($this->memcache->get($keys));
}
function makeEmpty()
{
$keys = $this->getAllKeys();
foreach ($keys as $value) {
$this->delete($value);
}
$this->delete("real");
$this->delete("front");
$this->delete("size");
$this->delete("maxSize");
}
private function getAllKeys()
{
if ($this->isEmpty())
{
return array();
}
$keys[] = $this->getKeyByPos($this->front);
for ($pos = ($this->front + 1) % $this->maxSize; $pos != $this->real; $pos = ($pos + 1) % $this->maxSize)
{
$keys[] = $this->getKeyByPos($pos);
}
return $keys;
}
private function add($pos, $data)
{
$this->memcache->add($this->getKeyByPos($pos), $data);
return $this;
}
private function increment($pos)
{
return $this->memcache->increment($this->getKeyByPos($pos));
}
private function decrement($pos)
{
$this->memcache->decrement($this->getKeyByPos($pos));
}
private function set($pos, $data)
{
$this->memcache->set($this->getKeyByPos($pos), $data);
return $this;
}
private function get($pos)
{
return $this->memcache->get($this->getKeyByPos($pos));
}
private function delete($pos)
{
return $this->memcache->delete($this->getKeyByPos($pos));
}
private function getKeyByPos($pos)
{
return $this->prefix . $this->name . $pos;
}
}

php  google 风格分页代码
public function showCtrlPanel_g($halfPer = 5) {
  
  $re = '<div class="pageMore">
   <ul>
    <li><span>'.$this->lineCount.'条</span></li>
    <li><span>'.$this->currentPage.'/'.$this->pageCount.'页</span></li>';
  if($this->currentPage-$halfPer >1){
   $re .= '<li><a href="'.$this->fileName.'pageno=1"><span>1</span></a></li>';
   if($this->currentPage-$halfPer*2 >1){
    $re .= '<li><a href="'.$this->fileName.'pageno='.($this->currentPage-$halfPer*2).'"><span>...</span></a></li>';
   }else{
    $re .= '<li><a href="'.$this->fileName.'pageno=1"><span>...</span></a></li>';
   }
  }
  for ( $i = $this->currentPage - $halfPer,$i > 1 || $i = 1 , $j = $this->currentPage + $halfPer, $j < $this->pageCount || $j = $this->pageCount;$i <= $j ;$i++ )
  {
   $re .= $i ==  $this->currentPage
    ? '<li class="linkOn"><a href="'.$this->fileName.'pageno='.$i.'"><span>'.$i.'</span></a></li>'." "
    : '<li><a href="'.$this->fileName.'pageno='.$i.'"><span>'.$i.'</span></a></li>'." ";
  }
  if($this->currentPage+$halfPer < $this->pageCount){
   if($this->currentPage+$halfPer*2 < $this->pageCount){
    $re .= '<li><a href="'.$this->fileName.'pageno='.($this->currentPage+$halfPer*2).'"><span>...</span></a></li>';
   }else{
    $re .= '<li><a href="'.$this->fileName.'pageno='.$this->pageCount.'"><span>...</span></a></li>';
   }
   $re .= '<li><a href="'.$this->fileName.'pageno='.$this->pageCount.'"><span>'.$this->pageCount.'</span></a></li>';
  }
    
  $re .= ' 
   </ul>
  </div>';
  return $re;
 }

php 日期转换成日时截

private function toTimeStamp ($dateTimeString = NULL) {
  if (!$dateTimeString) {
   $dateTimeString = time();
  }
  $numeric = '';
  $add_space = false;
  for($i=0;$i<strlen($dateTimeString);$i++) {
   if(strpos('0123456789',$dateTimeString[$i])===false) {
    if($add_space) {
     $numeric .= ' ';
     $add_space = false;
    }
   } else {
    $numeric .= $dateTimeString[$i];
    $add_space = true;
   }
  }
  
  $numeric_array = explode(' ',$numeric,6);
  if(sizeof($numeric_array)<3 || ($numeric_array[0]==0 && $numeric_array[1]==0 && $numeric_array[2]==0)) {
   throw new Exception($dateTimeString . ' is an invalid parameter', 5);
  } else {
   $result = mktime(intval($numeric_array[3]), intval($numeric_array[4]), intval($numeric_array[5]),
        intval($numeric_array[1]), intval($numeric_array[2]), intval($numeric_array[0])) ;
  }
  
  return $result;
 
 }

class PageCache {

 /**
  * @var string $file 缓存文件地址
  * @access public
  */
 public $file;
 
 /**
  * @var int $cacheTime 缓存时间
  * @access public
  */
 public $cacheTime = 3600;
 
 /**
  * 构造函数
  * @param string $file 缓存文件地址
  * @param int $cacheTime 缓存时间
     */
 function __construct($file, $cacheTime = 3600) {
  $this->file = $file;
  $this->cacheTime = $cacheTime;
 }
 
 /**
  * 取缓存内容
  * @param bool 是否直接输出,true直接转到缓存页,false返回缓存内容
  * @return mixed
     */
 public function get($output = true) {
  if (is_file($this->file) && (time()-filemtime($this->file))<=$this->cacheTime && !$_GET['nocache']) {
   if ($output) {
    header('location:' . $this->file);
    exit;
   } else {
    return file_get_contents($this->file);
   }
  } else {
   return false;
  }
 }
 
 /**
  * 设置缓存内容
  * @param $content 内容html字符串
     */
 public function set($content) {
  $fp = fopen($this->file, 'w');
  fwrite($fp, $content);
  fclose($fp);
 }
}

[!--infotagslink--]

相关文章

  • PHP传值到不同页面的三种常见方式及php和html之间传值问题

    在项目开发中经常见到不同页面之间传值在web工作中,本篇文章给大家列出了三种常见的方式。接触PHP也有几个月了,本文总结一下这段日子中,在编程过程里常用的3种不同页面传值方法,希望可以给大家参考。有什么意见也希望大...2015-11-24
  • js修改input的type属性问题探讨

    js修改input的type属性有些限制。当input元素还未插入文档流之前,是可以修改它的值的,在ie和ff下都没问题。但如果input已经存在于页面,其type属性在ie下就成了只读属性了,不可以修改。...2013-10-19
  • Mysql常见问题集锦

    1,utf8_bin跟utf8_general_ci的区别 ci是 case insensitive, 即 "大小写不敏感", a 和 A 会在字符判断中会被当做一样的; bin 是二进制, a 和 A 会别区别对待. 例如你运行: SELECT * FROM table WHERE txt = 'a'...2013-10-04
  • Mysql大小写敏感的问题

    一、1 CREATE TABLE NAME(name VARCHAR(10)); 对这个表,缺省情况下,下面两个查询的结果是一样的:复制代码 代码如下: SELECT * FROM TABLE NAME WHERE name='clip'; SELECT * FROM TABLE NAME WH...2015-03-15
  • linux mint 下mysql中文支持问题

    一.mysql默认不支持中文,它的server和db默认是latin1编码.所以我们要将其改变为utf-8编码,因为utf-8包含了地球上大部分语言的二进制编码 1.关闭mysql服务 sudo /etc/init.d/mysql stop 2.修改mysql配置文件 mysql配...2015-10-21
  • MYSQL事务回滚的2个问题分析

    因此,正确的原子操作是真正被执行过的。是物理执行。在当前事务中确实能看到插入的记录。最后只不过删除了。但是AUTO_INCREMENT不会应删除而改变值。1、为什么auto_increament没有回滚?因为innodb的auto_increament的...2014-05-31
  • Mysql索引会失效的几种情况分析

    索引并不是时时都会生效的,比如以下几种情况,将导致索引失效: 1.如果条件中有or,即使其中有条件带索引也不会使用(这也是为什么尽量少用or的原因)  注意:要想使用or,又想让索引生效,只能将or条件中的每个列都加上索引 ...2014-06-07
  • Underscore源码分析

    Underscore 是一个 JavaScript 工具库,它提供了一整套函数式编程的实用功能,但是没有扩展任何 JavaScript 内置对象。这篇文章主要介绍了underscore源码分析相关知识,感兴趣的朋友一起学习吧...2016-01-02
  • C#使用队列(Queue)解决简单的并发问题

    这篇文章主要介绍了使用队列(Queue)解决简单的并发问题,讲解的很细致,喜欢的朋友们可以了解一下...2020-06-25
  • python 爬取京东指定商品评论并进行情感分析

    本文主要讲述了利用Python网络爬虫对指定京东商城中指定商品下的用户评论进行爬取,对数据预处理操作后进行文本情感分析,感兴趣的朋友可以了解下...2021-05-28
  • Fatal error: Cannot redeclare class 原因分析与解决办法

    我使用的都是php __autoload状态自动加载类的,今天好好的程序不知道怎么在运行时提示Fatal error: Cannot redeclare class 了,看是重复定义了类,下面我来分析一下解决办...2016-11-25
  • Google会不会取消PR的理由分析

    Google是这样介绍PageRank的:   Google 出类拔萃的地方在于专注开发“完美的搜索引擎”,联合创始人拉里&middot;佩奇将这种搜索引擎定义为可“确解用户...2017-07-06
  • windows 10 安装和使用中5个常见问题

    2015年7月29日0点起,Windows 10推送全面开启,Windows7、Windows8.1用户可以免费升级到Windows 10,用户也可以通过系统升级到Windows10,在这过程中,用户会遇到这样那样的问题,下面小编总结了windows 10 安装和使用中5个常见问题,需要的朋友可以参考下...2016-01-27
  • php中session常见问题分析

    PHP的session功能,一直为许多的初学者为难。就连有些老手,有时都被搞得莫名其妙。本文,将这些问题,做一个简单的汇总,以便大家查阅。 1. 错误提示 引用 代...2016-11-25
  • javascript学习指南之回调问题

    回调函数被认为是一种高级函数,一种被作为参数传递给另一个函数(在这称作"otherFunction")的高级函数,回调函数会在otherFunction内被调用(或执行)。回调函数的本质是一种模式(一种解决常见问题的模式),因此回调函数也被称为回调模式。...2016-04-25
  • json error: Use of overloaded operator [] is ambiguous错误的解决方法

    今天小编就为大家分享一篇关于json error: Use of overloaded operator [] is ambiguous错误的解决方法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧...2020-04-25
  • C++基于递归算法解决汉诺塔问题与树的遍历功能示例

    这篇文章主要介绍了C++基于递归算法解决汉诺塔问题与树的遍历功能,简单描述了递归算法的原理,并结合实例形式分析了基于递归算法解决汉诺塔问题与数的遍历相关操作技巧,需要的朋友可以参考下...2020-04-25
  • 关于PHP文件包含一些漏洞分析

    文章简单的分析了在php文件包含时inlcude的一个漏洞分析,下面希望对大家有点用处哦。 基本的文件包含漏洞: 代码如下 复制代码 <?php include...2016-11-25
  • php echo print print_r三者区别分析

    php教程 echo print print_r三者区别分析 echo是PHP语句, print和print_r是函数,语句没有返回值,函数可以有返回值(即便没有用) print() 只能打印出简单类型变量的...2016-11-25
  • PHP date函数显示1970-01-01问题详解

    我们使用date函数直接显示后面带有date("Y-m-d H:i:s",$t);发现显示的为1970-01-01了,这个问题对于新手来讲可能不好理解,但对于做过几年的高手来讲小菜了。 如date...2016-11-25