PHP并发 加悲观锁

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

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

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

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

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

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

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);
    }
}

 

你可能感兴趣的:(软件设计)