找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1251|回复: 0
打印 上一主题 下一主题

PHP 进程锁定问题分析研究

[复制链接]

2588

主题

2588

帖子

7694

积分

论坛元老

Rank: 8Rank: 8

积分
7694
跳转到指定楼层
楼主
发表于 2018-2-14 09:01:58 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

            1. 区分读锁定 和 写 锁定。
如果每次都使用 写锁定,那么连多个进程读取一个文件也要排队,这样的效率肯定不行。
2. 区分 阻塞 与 非 阻塞模式。
一般来说,如果一个进程在写一个文件的时候,另外一个进程应该被阻塞,但是,很多时候,我们可以先干点别的事情,
然后再判断一下是否有其他人在写文件,如果没有,再加入数据,这样的效率更高。
3. 修复了 锁定文件在linux 上的bug,特别是 在 gfs 文件系统上的bug。
代码如下:
[U]复制代码[/U] 代码如下:
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) 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;
}
}
}
?>

测试代码:
[U]复制代码[/U] 代码如下:
writeLock();
$lock->increment();
$lock->unlock();
while ($lock->get() writeLock();
$lock->increment(1);
$lock->unlock();
}
$t2 = microtime(true) - $t1;
echo $t2;
?>

我增加了一个 increment 的函数,可以实现简单的线程同步,让两个进程同时执行某段代码,当然,这个有一定的误差
这里的误差是 0.001s。
把这个类简单的用到 前面的memcache 消息队列中就可以实现 线程安全的消息队列。
            
            
您可能感兴趣的文章:
  • PHP 多进程 解决难题
  • phplock(php进程锁) v1.0 beta1
  • Linux下实现PHP多进程的方法分享
  • 解析PHP实现多进程并行执行脚本
  • 深入解析PHP中的(伪)多线程与多进程
  • PHP多进程编程实例
  • PHP使用pcntl_fork实现多进程下载图片的方法
  • PHP中使用Memache作为进程锁的操作类分享
  • 深入探究PHP的多进程编程方法
  • php中实现进程锁与多进程的方法
            
  • 分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    用户反馈
    客户端