title: How to manage concurrency problems in php?
body: <p>Method <code>processReport</code> may be called in parallel with the same argument. But processing should be done only once if two processes call <code>processReport</code> with the same $reportId at the same time. To resolve this concurrency problem I've created helper methods <code>isLocked</code>, <code>lock</code> and <code>unlock</code>. <code>lock</code> creates temporary file for the $reportId. <code>isLocked</code> checks if the temp file exists. If the file exists processing should not be done. But the thing is that two parallel processes call <code>processReport</code> in the same time with the same $reportId sometimes this strategy doesn't work and processing is done twice(this obviously happens because of using filesystem which is too slow). Since processes do not share memory I don't know how to solve this concurrency problem. Is there any way to avoid processing the same $reportId twice?</p>
  
  <pre><code>private function getLockFileName($reportId) {
      return sprintf('%s/%s.lock', sys_get_temp_dir(), $reportId);
  }
  
  private function isLocked($reportId) {
      return file_exists($this-&gt;getLockFileName($reportId));
  }
  
  private function lock($reportId) {
      touch($this-&gt;getLockFileName($reportId));
  }
  
  private function unlock($reportId) {
      unlink($this-&gt;getLockFileName($reportId));
  }
  
  public function processReport($reportId) {
      if ($this-&gt;isLocked($reportId)) return;
  
      $this-&gt;lock($reportId);
  
      // processing should be done only once for the same $reportId
  
      $this-&gt;unlock($reportId);
  }
  </code></pre>