title: Preventing deadlock caused by flock
body: <p>I am trying to simulate a file writing on a busy site. I have written a following code which eventually end up freezing computer.</p>
  
  <pre><code>$loop = 10000;
  $sleep = 500000;
  $i =0;
  
  while($i &lt; $loop) {
  
      $mtime = microtime();
      $mtime = explode(" ",$mtime);
      $mtime = $mtime[1] + $mtime[0];
      $starttime = $mtime; 
  
      $handler = fopen($file,"a+");
      if($handler) {
      if (flock($handler, LOCK_EX)) {
          $mtime = microtime();
          $mtime = explode(" ",$mtime);
          $mtime = $mtime[1] + $mtime[0];
          $endtime = $mtime;
          $totaltime = ($endtime - $starttime); 
  
          fwrite($handler,"Script 1 took $totaltime secs\n");
      }
  
      flock($handler, LOCK_UN);
      fclose($handler);
  }
  $i++;
  usleep($sleep);
  }
  </code></pre>
  
  <p>I can't use LOCK_NB because it will not work on windows. The code works fine if there are less than 13 processes execute the above code at the same. How do I cope with this deadlock situation?</p>