PHP并发 加悲观锁

php如何解决多线程读写同一文件

大家都知道,PHP是没有多线程概念的,尽管如此我们仍然可以用“不完美”的方法来模拟多线程。简单的说,就是队列处理。通过对文件进行加锁和解锁,来实现。当一个文件被一个用户操作时,该文件是被锁定的,其他用户只能等待,确实不够完美,但是也可以满足一些要求不高的应用。

上限判断,关键数据的写入扣钱之类

用到了Eaccelerator的内存锁和文件锁,原理:判断系统中是否安了EAccelerator如果有则使用内存锁,如果不存在,则进行文件锁。根据带入的key的不同可以实现多个锁直接的并行处理 ,类似Innodb的行级锁。

具体类如下:file_put_contents($file, $string, LOCK_EX );

<?php

/**
 * CacheLock 进程锁,主要用来进行cache失效时的单进程cache获取,防止过多的SQL请求穿透到数据库
 * 用于解决PHP在并发时候的锁控制,通过文件/eaccelerator进行进程间锁定
 * 如果没有使用eaccelerator则进行进行文件锁处理,会做对应目录下产生对应粒度的锁
 * 使用了eaccelerator则在内存中处理,性能相对较高
 * 不同的锁之间并行执行,类似mysql innodb的行级锁
 *
 */
class CacheLock
{
    //文件锁存放路径
    private $path = null;
    //文件句柄
    private $fp = null;
    //锁粒度,设置越大粒度越小
    private $hashNum = 100;
    //cache key
    private $name;
    //是否存在eaccelerator标志
    private $eAccelerator = false;

    /**
     * 构造函数
     * 传入锁的存放路径,及cache key的名称,这样可以进行并发
     * @param string $path 锁的存放目录
     * @param string $name cache key
     */
    public function __construct($name, $path = 'lock')
    {
        //判断是否存在eAccelerator,这里启用了eAccelerator之后可以进行内存锁提高效率
        $this->eAccelerator = function_exists("eaccelerator_lock");
        if (!$this->eAccelerator) {
            if (!is_dir($path)) { //目录设置写权限
                mkdir($path, 0777);
                chmod($path, 0777);
            }
            $this->path = realpath($path) . DIRECTORY_SEPARATOR . ($this->_mycrc32($name) % $this->hashNum) . '.txt';
        }
        $this->name = $name;
    }

    /**
     * crc32
     * crc32封装 相同的string会算出唯一值
     * @param string $string
     * @return int
     */
    private function _mycrc32($string)
    {
        $crc = abs(crc32($string));
        if ($crc & 0x80000000) {
            $crc ^= 0xffffffff;
            $crc += 1;
        }
        return $crc;
    }

    /**
     * 加锁
     * Enter description here ...
     */
    public function lock()
    {
        //如果无法开启ea内存锁,则开启文件锁
        if (!$this->eAccelerator) {
            //配置目录权限可写
            $this->fp = fopen($this->path, 'w+');
            if ($this->fp === false) {
                return false;
            }
            return flock($this->fp, LOCK_EX);
        } else {
            return eaccelerator_lock($this->name);
        }
    }

    /**
     * 解锁
     * Enter description here ...
     */
    public function unlock()
    {
        if (!$this->eAccelerator) {
            if ($this->fp !== false) {
                flock($this->fp, LOCK_UN);
                $this->deleteCache();
            }
            //进行关闭
            fclose($this->fp);
        } else {
            return eaccelerator_unlock($this->name);
        }
    }
    //删除零时文件
    private function deleteCache()
    {
        clearstatcache(); //清除文件状态缓存

        //删除1小时前的文件
        $cacheDir = dirname($this->path);
        $files = scandir($cacheDir);
        foreach ($files as $file) {
            if (strlen($file) > 2 && time() > (filemtime($cacheDir . DIRECTORY_SEPARATOR . $file) + 3600)) {
                @unlink($cacheDir . DIRECTORY_SEPARATOR . $file);
            }
        }
    }
}
?>

 使用如下:

$lock = new CacheLock($orderNo); //要排队访问文件要相同,即name
$lock->lock();
//logic here
$lock->unlock();

asfd

<?php
 
/** 
 * LockSystem.php 
 * 
 * php锁机制
 * 
//创建锁(推荐使用MemcacheLock)
$lockSystem = new LockSystem(LockSystem::LOCK_TYPE_MEMCACHE);             

//获取锁
$lockKey = 'pay'.$userId;
$lockSystem->getLock($lockKey, 8);

//释放锁
$lockSystem->releaseLock($lockKey);
 * 
 */ 
 
class LockSystem
{
    const LOCK_TYPE_DB = 'SQLLock';
    const LOCK_TYPE_FILE = 'FileLock';
    const LOCK_TYPE_MEMCACHE = 'MemcacheLock';
    
    private $_lock = null;
    private static $_supportLocks = array('FileLock', 'SQLLock', 'MemcacheLock');  
    
    public function __construct($type, $options = array()) 
    {
        if(false == empty($type))
        {
            $this->createLock($type, $options);
        }
    }   
 
    public function createLock($type, $options=array())
    {
        if (false == in_array($type, self::$_supportLocks))
        {
            throw new Exception("not support lock of ${type}");
        }
        $this->_lock = new $type($options);
    }
    
    public function getLock($key, $timeout = ILock::EXPIRE)
    {
        if (false == $this->_lock instanceof ILock)  
        {
            throw new Exception('false == $this->_lock instanceof ILock');          
        }  
        $this->_lock->getLock($key, $timeout);   
    }
    
    public function releaseLock($key)
    {
        if (false == $this->_lock instanceof ILock)  
        {
            throw new Exception('false == $this->_lock instanceof ILock');          
        }  
        $this->_lock->releaseLock($key);         
    }   
}
 
interface ILock
{
    const EXPIRE = 5;
    public function getLock($key, $timeout=self::EXPIRE);
    public function releaseLock($key);
}
 
class FileLock implements ILock
{
    private $_fp;
    private $_single;
 
    public function __construct($options)
    {
        if (isset($options['path']) && is_dir($options['path']))
        {
            $this->_lockPath = $options['path'].'/';
        }
        else
        {
            $this->_lockPath = '/tmp/';
        }
       
        $this->_single = isset($options['single'])?$options['single']:false;
    }
 
    public function getLock($key, $timeout=self::EXPIRE)
    {
        $startTime = Timer::getTimeStamp();
 
        $file = md5(__FILE__.$key);
        $this->fp = fopen($this->_lockPath.$file.'.lock', "w+");
        if (true || $this->_single)
        {
            $op = LOCK_EX + LOCK_NB;
        }
        else
        {
            $op = LOCK_EX;
        }
        if (false == flock($this->fp, $op, $a))
        {
            throw new Exception('failed');
        }
       
	    return true;
    }
 
    public function releaseLock($key)
    {
        flock($this->fp, LOCK_UN);
        fclose($this->fp);
    }
}
 
class SQLLock implements ILock
{
    public function __construct($options)
    {
        $this->_db = new mysql(); 
    }
 
    public function getLock($key, $timeout=self::EXPIRE)
    {       
        $sql = "SELECT GET_LOCK('".$key."', '".$timeout."')";
        $res =  $this->_db->query($sql);
        return $res;
    }
 
    public function releaseLock($key)
    {
        $sql = "SELECT RELEASE_LOCK('".$key."')";
        return $this->_db->query($sql);
    }
}
 
class MemcacheLock implements ILock
{
    public function __construct($options)
    {
        
        $this->memcache = new Memcache();
    }
 
    public function getLock($key, $timeout=self::EXPIRE)
    {     
        $waitime = 20000;
        $totalWaitime = 0;
        $time = $timeout*1000000;
        while ($totalWaitime < $time && false == $this->memcache->add($key, 1, $timeout)) 
        {
            usleep($waitime);
            $totalWaitime += $waitime;
        }
        if ($totalWaitime >= $time)
            throw new Exception('can not get lock for waiting '.$timeout.'s.');
 
    }
 
    public function releaseLock($key)
    {
        $this->memcache->delete($key);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值