2016-04-21 29 views

回答

0

請參考此答案。 file locking in php

這涵蓋了鎖定部分。但是,要訪問該文件,需要執行一個循環,直到釋放鎖。這是一個示例算法。

define(MAX_SLEEP, 3); // Decide a good value for number of tries 
    $sleep = 0; // Initialize value, always a good habit from C :) 
    $done = false; // Sentinel value 
    $flock = new Flock; // You need to implement this class 
    do { 
     if (! $flock->locked()) { // We have a green light 
      $flock->lock(); // Lock right away 

      //DO STUFF; 

      $flock->unlock(); // Release the lock so others can access 
      $done = true; // Allows the loop to exit 

     } else if ($sleep++ > MAX_SLEEP) { // Giving up, cannot write 
      // Handle exception, there are many possibilities: 
      //  Log exception and do nothing (definitely log) 
      //  Force a write 
      //  See if another process has been running for too long 
      //  Check for timestamp of the lock file, maybe left behind after a reboot 
     } else { 
      sleep(SLEEP_TIME); 
     } 
    } while(! $done);