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