当前位置:网站首页>PHP file lock

PHP file lock

2022-06-24 09:45:00 BigChen_ up

  1. cpu The thread of : It means how many things can be done at the same time .
  2. Resources are exclusive : A resource can only be used by one thread at a time , You need to add Exclusive lock , To prevent others from using .
  3. Shared lock : A resource can be viewed by many people , But you can't change it when checking .
// When writing documents ,  You need to add   Exclusive lock ,  There is a disorder in placing other threads to write at the same time 
function put($path, $data) {
    $handle = fopen($path, 'w');

    //flock();  Lock .  Parameters 2 Represents the type of lock .
    //LOCK_EX:  Exclusive lock 
    if (flock($handle, LOCK_EX)) {
        // Write content 
        fwrite($handle, $data);
        //LOCK_UN:  Unlock 
        flock($handle, LOCK_UN);
    }
    fclose($handle);
}

// Shared lock :  When the document is read ,  Other threads can only read and cannot change 
function get($path) {
    $handle = fopen($path, 'r');

    //LOCK_SH: share share 
    if (flock($handle, LOCK_SH)) {
        //fread()  Read by byte 
        $text = fread($handle, filesize($path));
        // Unlock 
        flock($handle, LOCK_UN);
    }
    fclose($handle);
    return $text;
}

// echo get('d:/php7.0/php.ini');
put('abc.txt', 'AAAAAAAAAAA');
原网站

版权声明
本文为[BigChen_ up]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240807401985.html