php操作锁

class FileOperationLock{
	const FILE_LOCK='php_lock.sock';
	
	private $_is_lock=false;
	
	private $_fp=null;
	
	public function lock(){
		if ($this->_is_lock!==false) {
			return false;
		}
		if (!$this->_fp=fopen(self::FILE_LOCK, 'w+b')){
			return $this->_is_lock;
		}
		if (flock($this->_fp, LOCK_EX)) {
			$this->_is_lock=true;
		}
		return $this->_is_lock;
	}
	
	public function unlock(){
		if ($this->_is_lock===false||!$this->_fp) {
			return true;
		}
		flock($this->_fp,LOCK_UN);
		$this->_is_lock=false;
		fclose($this->_fp);
		return true;
	}
	
	public function isLock(){
		return $this->_is_lock;
	}
}

class SemOperationLock{
	private $_is_lock=false;
	
	private $_sem_key='';
	
	private $_sem_lock=null;
	
	public function __construct(){
		if (!function_exists('sem_get')) {
			throw new Exception('can`t use this kind of lock');
		}
		$this->_sem_key=ftok(__FILE__, 'a');
		$this->_sem_lock=sem_get($this->_sem_key,1);
	}
	
	public function lock(){
		if (sem_acquire($this->_sem_lock)) {
			$this->_is_lock=true;
		}
		return $this->_is_lock;
	}
	
	public function unlock(){
		if ($this->_is_lock===false||!$this->_sem_lock) {
			return true;
		}
		if (sem_release($this->_sem_lock)) {
			$this->_is_lock=false;
			return true;
		}
		return false;
	}
	
	public function isLock(){
		return $this->_is_lock;
	}
	
	public function __destruct(){
		sem_remove($this->_sem_lock);
	}
}

class MemcacheOperationLock {
	
	private $_is_lock=false;
	
	private $_memcache=null;
	
	public function __construct($configs){
		if (extension_loaded('memcache')) {
			$this->_memcache=new Memcache();
			if(!$this->_memcache->connect($configs[0],$configs[1])){
				throw new Exception('can`t connect to memcache server');
			}
		}else{
			throw new Exception('extension memcache not loaded');
		}
	}
	
	public function lock(){
		if ($this->_is_lock!==false) {
			return false;
		}
		if ($this->_memcache->add('php_lock_key',1,false,0)){
			$this->_is_lock=true;
		}else{
			return false;
		}
		return $this->_is_lock;
	}
	
	public function unlock(){
		if ($this->_is_lock===false||!$this->_memcache) {
			return true;
		}
		$this->_memcache->delete('php_lock_key');
		$this->_is_lock=false;
		$this->_memcache->close();
		return true;
	}
	
	public function isLock(){
		return $this->_is_lock;
	}
}

git项目地址:https://github.com/mfdgood/phpoperationlock.git

使用方法见git的readme文件

第一次自己写东西,不完善不好用请见谅 有觉得可以改进的地方可以在下面留言,在我能力范围之内的我会去修改

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值