Most reliable & safe method of preventing race conditions in PHP

In fact, i think there is no need for a complex mutex / semaphore whatever solution.

Form keys stored in a PHP $_SESSION are all you need. As a nice side effect, this method also protects your form against CSRF attacks.

In PHP, sessions are locked by aquiring a POSIX flock() and PHP's session_start() waits until the user session is released. You just have to unset() the form key on the first valid request. The second request has to wait until the first one releases the session.

However, when running in a (not session or source ip based) load balancing scenario involving multiple hosts things are getting more complicated. For such a scenario, i'm sure you will find a valuable solution in this great paper: http://thwartedefforts.org/2006/11/11/race-conditions-with-ajax-and-php-sessions/

I reproduced your use case with the following demonstration. just throw this file onto your webserver and test it:

<?php
session_start();
if (isset($_REQUEST['do_stuff'])) {
  // do stuff
  if ($_REQUEST['uniquehash'] == $_SESSION['uniquehash']) {
    echo "valid, doing stuff now ... "; flush();
    // delete formkey from session
    unset($_SESSION['uniquehash']);
    // release session early - after committing the session data is read-only
    session_write_close();
    sleep(20);  
    echo "stuff done!";
  }
  else {
    echo "nope, {$_REQUEST['uniquehash']} is invalid.";
  }     
}
else {
  // show form with formkey
  $_SESSION['uniquehash'] = md5("foo".microtime().rand(1,999999));
?>
<html>
<head><title>session race condition example</title></head>
<body>
  <form method="POST">
    <input type="hidden" name="PHPSESSID" value="<?=session_id()?>">
    <input type="text" name="uniquehash" 
      value="<?= $_SESSION['uniquehash'] ?>">
    <input type="submit" name="do_stuff" value="Do stuff!">
  </form>
</body>
</html>
<?php } ?>

An interesting question you have but you don't have any data or code to show.

For 80% of cases the chances of anything nasty happening because of PHP itself are virtually zero if you follow the standard procedures and practices regarding stopping users from submitting forms multiple times, which applies to nearly every other setup, not just PHP.

If you're the 20% and your environment demands it, then one option is using message queues which I'm sure you are familiar with. Again, this idea is language agnostic. Nothing to do with languages. Its all about how data moves around.