PHP file Lock Write instance parse _php tips

Source: Internet
Author: User

This article is an example of the PHP file writing method to respond to multithreaded 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)) {//Exclusive locking
      $timeout-; 
      Sleep (1); 
    } 
  } 
  if ($timeout > 0) { 
    fwrite ($handle, $text. \ n '); 
    Flock ($handle, lock_un); 
    Fclose ($handle); Release lock operation return
    true; 
  } 
  return false; 
}

Where the flock (int $handle, int $operation) function operation handle must be a file pointer that is already open.

Operation can be one of the following values:

To obtain a shared lock (read program), set the operation to Lock_sh (PHP 4.0.1 Previous version is 1).
To obtain an exclusive lock (written program), set the operation to LOCK_EX (2 in the previous version of PHP 4.0.1).
To release the lock (either shared or exclusive), set the operation to Lock_un (3 in the previous version of PHP 4.0.1).
If you do not want flock () to be blocked when locked, add LOCK_NB to Operation (set to 4 in previous versions of PHP 4.0.1).

In addition, the fclose () is used to release the lock operation, which is invoked when the code finishes executing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.