Home > Backend Development > PHP Tutorial > PHP file lock writing example analysis, _PHP tutorial

PHP file lock writing example analysis, _PHP tutorial

WBOY
Release: 2016-07-13 10:23:27
Original
884 people have browsed it

PHP file lock writing instance analysis,

This article describes the PHP file writing method with examples to cope with multi-threaded writing. The specific code is as follows:

function file_write($file_name, $text, $mode='a', $timeout=30){ 
  $handle = fopen($file_name, $mode); 
  while($timeout>0){ 
    if ( flock($handle, LOCK_EX) ) { // 排它性的锁定
      $timeout--; 
      sleep(1); 
    } 
  } 
  if ( $timeout > 0 ){ 
    fwrite($handle, $text.'\n'); 
    flock($handle, LOCK_UN); 
    fclose($handle); //释放锁定操作
    return true; 
  } 
  return false; 
}

Copy after login

Among themthe handle operated by the flock(int $handle, int $operation) function must be an open file pointer.

operation can be one of the following values:

To obtain a shared lock (reading program), set operation to LOCK_SH (set to 1 in versions prior to PHP 4.0.1).
To obtain an exclusive lock (writing program), set operation to LOCK_EX (set to 2 in versions prior to PHP 4.0.1).
To release a lock (whether shared or exclusive), set operation to LOCK_UN (set to 3 in versions prior to PHP 4.0.1).
If you don't want flock() to block on lock, add LOCK_NB to the operation (set to 4 in versions prior to PHP 4.0.1).

In addition, fclose() is used to release the lock operation and is called when the code execution is completed.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/840627.htmlTechArticleAnalysis of PHP file lock writing examples. This article uses examples to describe the PHP file writing method to cope with multi-threaded writing. Enter, the specific code is as follows: function file_write($file_name, $text, $mode='...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template