title: Concurrency with two files and two AJAX calls
body: <p>I've a concurrency problem when using two different AJAX function accessing two different files.</p>
  
  <p><strong>I cannot use a database to do the following task, it have to do it using these files only</strong></p>
  
  <h2><strong>Problem</strong></h2>
  
  <p>I've two files, <strong>A</strong> and <strong>B</strong> :</p>
  
  <pre><code>// A content :
  1 2 3 4
  // B content :
  5 6 7 8
  </code></pre>
  
  <p>I've two AJAX calls, <code>func_a</code> and <code>func_b</code></p>
  
  <p><code>func_a</code> add the last value from <strong>A</strong> to <strong>B</strong> and add the last value from <strong>B</strong> to <strong>A</strong> </p>
  
  <pre><code>// Result after func_a 
  A : 1 2 3 4 8
  B : 5 6 7 8 4
  </code></pre>
  
  <p><code>func_b</code> add the last value from <strong>B</strong> to <strong>A</strong> and add the last value from <strong>A</strong> to <strong>B</strong></p>
  
  <p>I thought about concurrency and in any cases a problem would appears. Firstly, if I just read and close each file before opening the next one, and <code>func_a</code> + <code>func_b</code> are used at the same time, I could get the following result :</p>
  
  <pre><code>A : 1 2 3 4 8 8
  B : 5 6 7 8 4 4
  </code></pre>
  
  <p>But the wanted result would be :</p>
  
  <pre><code>A : 1 2 3 4 8 4
  B : 5 6 7 8 4 8
  </code></pre>
  
  <p>Moreoever, I think I can't keep files opened during the whole process, or I could get a deadlock.</p>
  
  <pre><code>func_a open A;
  func_b open B;
  func_a can't open B, waits forever;
  func_b can't open A, waits forever;
  </code></pre>
  
  <p>I'm pretty sure PhP Mutex is not what I'm looking for, because it couldn't work between two AJAX calls. Also, let's say that returning "Sorry, couldn't open file B" is not an option, it has to work at first try.</p>
  
  <p>Every solution I thought about so far wouldn't work :</p>
  
  <p>using a <code>mutex.lock</code> temporary file to check if the ressources are used results on the same problem.</p>
  
  <p>Maybe there is a way to check if Apache is currently running <code>func_a</code> so <code>func_b</code> waits ? (Resource starvation wouldn't be possible in that case) </p>
  
  <p>I'm not too used to concurrency mathers and everything I found on the Internet was related to database and/or mutex.</p>
  
  <p>Any help would be very much appreciated, maybe there is an easy way I didn't think about ? </p>
  
  <p>Thanks.</p>