title: prevent multiple instances of script in same time
body: <p>PHP by default does not have multi threading for our apps, but it is possible, that 2 or more users will click same link in same time or, as in my case, multiple API requests are send in same time.</p>
  <p>I have script, that creates quite big file when first user does something.</p>
  <p>This is what I have in my code:</p>
  <pre class="lang-php prettyprint-override"><code>if (!file_exists($tmp_file)){
     write_file();
  }
  </code></pre>
  <p>but sometimes multiple instances of that script are launched in same time in 2 separate Apache threads. In that case, it might happen, that file_exists() will return false, but 0.00001s later, when i'm trying to write that file, it already exists, because it was created by simultaneously running script.</p>
  <p>Is there any way to detect such situation and prevent it?</p>
  <p>I know I can catch an error and simply not display it to the user, but I prefer not to have any error at all.</p>