• PHP文件锁同步实例


    该文件锁达到的效果是:

    PHP语言中:多个请求,在同一时间段内,访问同一段代码,改代码只能同时处理一个请求,其它的请求排队等候,等一个请求处理完后,再依次处理剩余的请求。

    类似于Java的synchronized线程同步。

    实现的步骤如下(使用过程中需要注意下文件锁所在路径需要有写权限):

    1、编辑一个进程锁类CacheLock.class.php

     eAccelerator = function_exists("eaccelerator_lock");
            if (!$this -> eAccelerator) {
                $this -> path = $path.($this -> _mycrc32($name) % $this -> hashNum).
                '.txt';
            }
            $this -> name = $name;
        }
        /** 
         * crc32 
         * crc32封装 
         * @param int $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) {
                //配置目录权限可写 
                //echo $this -> path;
                //die();
                $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);
                    clearstatcache();
                }
                //进行关闭 
                fclose($this -> fp);
            } else {
                return eaccelerator_unlock($this -> name);
            }
        }
    }

    2、在 CacheLock.class.php文件的同级目录下新建一个lock的空文件夹

    至此,已经配置完成。接下来就是测试使用。


    3、分别建立讲个php文件index.php和index2.php。

    index.php:

    lock(); 
    	for($a=1;$a<5;$a++){
    		file_put_contents("test.txt", "***********第一个文件[" . $a . "].\n", FILE_APPEND);
    		sleep(2);
    		echo '正在写入第  ' . $a . '个文件。';
    	}
    	/*	这里是要同步的代码块	结束	*/
    	$lock->unlock(); 
    ?>

    index2.php:

    lock(); 
    	for($a=1;$a<5;$a++){
    		file_put_contents("test.txt", "第二个文件[" . $a . "].\n", FILE_APPEND);
    		sleep(2);
    		echo '正在写入第  ' . $a . '个文件。';
    	}
    	/*	这里是要同步的代码块	结束	*/
    	$lock->unlock(); 
    ?>

    这两个文件代码几乎一模一样,只是输出文件(file_put_contents)的内容不一样,循环4次写入文件内容。

  • 相关阅读:
    我是如何每天赚到 5 美元的被动收入(使用 Android和iOS 应用程序)
    Java | 多线程综合练习
    QScintilla代码跳转时indicator工作不正确的问题
    ZooKeeper-实战
    MySQL读写分离
    Spring Mvc 拦截器详解
    不看后悔!第一本全面详解Transformer的综合性书籍!284页pdf下载
    Java IO之网络的简介说明
    312页18万字数字化校园总体建设方案
    SQL基础理论篇(八):视图
  • 原文地址:https://blog.csdn.net/liuliuhelingdao/article/details/127564422