Index: includes/bootstrap.inc
===================================================================
--- includes/bootstrap.inc	(revision 7577)
+++ includes/bootstrap.inc	(working copy)
@@ -1054,6 +1054,8 @@
         exit;
       }
       // Prepare for non-cached page workflow.
+      require_once variable_get('lock_inc', './includes/lock.inc');
+      lock_init();
       drupal_page_header();
       break;
 
Index: includes/lock.inc
===================================================================
--- includes/lock.inc	(revision 0)
+++ includes/lock.inc	(revision 0)
@@ -0,0 +1,234 @@
+<?php
+// $Id$
+
+/**
+ * @file
+ * A database-mediated implementation of a locking mechanism.
+ */
+
+/**
+ * @defgroup lock Functions to coordinate long-running operations across requests.
+ * @{
+ * In most environments, multiple Drupal page requests (a.k.a. threads or
+ * processes) will execute in parallel. This leads to potential conflicts or
+ * race conditions when two requests execute the same code at the same time. A
+ * common example of this is a rebuild like menu_rebuild() where we invoke many
+ * hook implementations to get and process data from all active modules, and
+ * then delete the current data in the database to insert the new afterwards.
+ *
+ * This is a cooperative, advisory lock system. Any long-running operation
+ * that could potentially be attempted in parallel by multiple requests should
+ * try to acquire a lock before proceeding. By obtaiing a lock, one request
+ * notifies any other requests that a specific opertation is in progress which
+ * must not be executed in parallel.
+ *
+ * To use this API, pick a unique name for the lock. A sensible choice is the
+ * name of the function performing the operation. A very simple example use of
+ * this API:
+ * @code
+ * function mymodule_long_operation() {
+ *   if (lock_acquire('mymodule_long_operation')) {
+ *     // Do the long operation here.
+ *     // ...
+ *     lock_release('mymodule_long_operation');
+ *   }
+ * }
+ * @endcode
+ *
+ * If a function acquires a lock it should always release it when the
+ * operation is complete by calling lock_release(), as in the example.
+ *
+ * A function that has acquired a lock may attempt to renew a lock (extend the
+ * duration of the lock) by calling lock_acquire() again during the operation.
+ * Failure to renew a lock is indicative that another request has acquired
+ * the lock, and that the current operation may need to be aborted.
+ *
+ * If a function fails to acquire a lock it may either immediately return, or
+ * it may call lock_wait() if the rest of the current page request requires
+ * that the operation in question be complete.  After lock_wait() returns,
+ * the function may again attempt to acquire the lock, or may simply allow the
+ * page request to proceed on the  assumption that a parallel request completed
+ * the operation.
+ *
+ * lock_acquire() and lock_wait() will automatically break (delete) a lock
+ * whose duration has exceeded the timeout specified when it was acquired.
+ *
+ * A function that has acquired a lock may attempt to renew a lock (extend the
+ * duration of the lock) by calling lock_acquire() again during the operation.
+ * Failure to renew a lock is indicative that another request has acquired
+ * the lock, and that the current operation may need to be aborted.
+ *
+ * Alternative implementations of this API (such as APC) may be substituted
+ * by setting the 'lock_inc' variable to an alternate include filepath.  Since
+ * this is an API intended to support alternative implementations, code using
+ * this API should never rely upon specific implementation details (for example
+ * no code should look for or directly modify a lock in the {semaphore} table).
+ */
+
+/**
+ * Initialize the locking system.
+ */
+function lock_init() {
+  global $locks;
+
+  $locks = array();
+}
+
+/**
+ * Helper function to get this request's unique id.
+ */
+function _lock_id() {
+  static $lock_id;
+
+  if (!isset($lock_id)) {
+    // Assign a unique id.
+    $lock_id = uniqid(mt_rand(), TRUE);
+    // We only register a shutdown function if a lock is used.
+    register_shutdown_function('lock_release_all', $lock_id);
+  }
+  return $lock_id;
+}
+
+/**
+ * Acquire (or renew) a lock, but do not block if it fails.
+ *
+ * @param $name
+ *   The name of the lock.
+ * @param $timeout
+ *   A number of seconds (float) before the lock expires.
+ * @return
+ *   TRUE if the lock was acquired, FALSE if it failed.
+ */
+function lock_acquire($name, $timeout = 30.0) {
+  global $locks;
+
+  // Insure that the timeout is at least 1 ms.
+  $timeout = max($timeout, 0.001);
+  list($usec, $sec) = explode(' ', microtime());
+  $expire = (float)$usec + (float)$sec + $timeout;
+  if (isset($locks[$name])) {
+    // Try to extend the expiration of a lock we already acquired.
+    if (!db_result(db_query("UPDATE {semaphore} SET expire = %f WHERE name = '%s' AND value = '%s'", $expire, $name, _lock_id()))) {
+      // The lock was broken.
+      unset($locks[$name]);
+    }
+  }
+  else {
+    // Optimistically try to acquire the lock, then retry once if it fails.
+    // The first time through the loop cannot be a retry.
+    $retry = FALSE;
+    // We always want to do this code at least once.
+    do {
+      if (@db_query("INSERT INTO {semaphore} (name, value, expire) VALUES ('%s', '%s', %f)", $name, _lock_id(), $expire)) {
+        // We track all acquired locks in the global variable.
+        $locks[$name] = TRUE;
+        // We never need to try again.
+        $retry = FALSE;
+      }
+      else {
+        // Suppress the error. If this is our first pass through the loop,
+        // then $retry is FALSE. In this case, the insert must have failed
+        // meaning some other request acquired the lock but did not release it.
+        // We decide whether to retry by checking lock_may_be_available()
+        // Since this will break the lock in case it is expired.
+        $retry = $retry ? FALSE : lock_may_be_available($name);
+      }
+      // We only retry in case the first attempt failed, but we then broke
+      // an expired lock.
+    } while ($retry);
+  }
+  return isset($locks[$name]);
+}
+
+/**
+ * Check if lock acquired by a different process may be available.
+ *
+ * If an existing lock has expired, it is removed.
+ *
+ * @param $name
+ *   The name of the lock.
+ * @return
+ *   TRUE if there is no lock or it was removed, FALSE otherwise.
+ */
+function lock_may_be_available($name) {
+  $lock = db_fetch_array(db_query("SELECT expire, value FROM {semaphore} WHERE name = '%s'", $name));
+  if (!$lock) {
+    return TRUE;
+  }
+  $expire = (float) $lock['expire'];
+  list($usec, $sec) = explode(' ', microtime());
+  $now = (float)$usec + (float)$sec;
+  if ($now > $lock['expire']) {
+    // We check two conditions to prevent a race condition where another
+    // request acquired the lock and set a new expire time.  We add a small
+    // number to $expire to avoid errors with float to string conversion.
+    db_query("DELETE FROM {semaphore} WHERE name = '%s' AND value = '%s' AND expire <= %f", $name, $lock['value'], 0.0001 + $expire);
+    return (bool)db_affected_rows();
+  }
+  return FALSE;
+}
+
+/**
+ * Wait for a lock to be available.
+ *
+ * This function may be called in a request that fails to acquire a desired
+ * lock. This will block further execution until the lock is available or the
+ * specified delay in seconds is reached.  This should not be used with locks
+ * that are acquired very frequently, since the lock is likely to be acquired
+ * again by a different request during the sleep().
+ *
+ * @param $name
+ *   The name of the lock.
+ * @param $delay
+ *   The maximum number of seconds to wait, as an integer.
+ * @return
+ *   TRUE if the lock holds, FALSE if it is available.
+ */
+function lock_wait($name, $delay = 30) {
+
+  while ($delay--) {
+    // This function should only be called by a request that failed to get a
+    // lock, so we sleep first to give the parallel request a chance to finish
+    // and release the lock.
+    sleep(1);
+    if (lock_may_be_available($name)) {
+      // No longer need to wait.
+      return FALSE;
+    }
+  }
+  // The caller must still wait longer to get the lock.
+  return TRUE;
+}
+
+/**
+ * Release a lock previously acquired by lock_acquire().
+ *
+ * This will release the named lock if it is still held by the current request.
+ *
+ * @param $name
+ *   The name of the lock.
+ */
+function lock_release($name) {
+  global $locks;
+
+  unset($locks[$name]);
+  db_query("DELETE FROM {semaphore} WHERE name = '%s' AND value = '%s'", $name, _lock_id());
+}
+
+/**
+ * Release all previously acquired locks.
+ */
+function lock_release_all($lock_id = NULL) {
+  global $locks;
+
+  $locks = array();
+  if (empty($lock_id)) {
+    $lock_id = _lock_id();
+  }
+
+  db_query("DELETE FROM {semaphore} WHERE value = '%s'", _lock_id());
+}
+
+/**
+ * @} End of "defgroup locks".
+ */
Index: includes/menu.inc
===================================================================
--- includes/menu.inc	(revision 7577)
+++ includes/menu.inc	(working copy)
@@ -1669,15 +1669,28 @@
  * is different and leaves stale data in the menu tables.
  */
 function menu_rebuild() {
-  variable_del('menu_rebuild_needed');
+  if (!lock_acquire('menu_rebuild')) {
+    // Wait for another request that is already doing this work.
+    // We choose to block here since otherwise the router item may not 
+    // be avaiable in menu_execute_active_handler() resulting in a 404.
+    lock_wait('menu_rebuild');
+    return FALSE;
+  }
+
   $menu = menu_router_build(TRUE);
   _menu_navigation_links_rebuild($menu);
   // Clear the menu, page and block caches.
   menu_cache_clear_all();
   _menu_clear_page_cache();
+  
   if (defined('MAINTENANCE_MODE')) {
     variable_set('menu_rebuild_needed', TRUE);
   }
+  else {
+    variable_del('menu_rebuild_needed');
+  }
+  lock_release('menu_rebuild');
+  return TRUE;
 }
 
 /**
Index: modules/system/system.install
===================================================================
--- modules/system/system.install	(revision 7577)
+++ modules/system/system.install	(working copy)
@@ -956,6 +956,31 @@
     'primary key' => array('mlid'),
     );
 
+  $schema['semaphore'] = array(
+    'description' => 'Table for holding semaphores, locks, flags, etc. that cannot be stored as Drupal variables since they must not be cached.',
+    'fields' => array(
+      'name' => array(
+        'description' => 'Primary Key: Unique name.',
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE,
+        'default' => ''),
+      'value' => array(
+        'description' => 'A value.',
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE,
+        'default' => ''),
+      'expire' => array(
+        'description' => 'A Unix timestamp with microseconds indicating when the semaphore should expire.',
+        'type' => 'float',
+        'size' => 'big',
+        'not null' => TRUE),
+      ),
+    'indexes' => array('expire' => array('expire')),
+    'primary key' => array('name'),
+    );
+
   $schema['sessions'] = array(
     'description' => "Drupal's session handlers read and write into the sessions table. Each record represents a user session, either anonymous or authenticated.",
     'fields' => array(
@@ -2598,6 +2623,37 @@
 }
 
 /**
+ * Add semaphore table.
+ */
+function system_update_6052() {
+  $ret = array();
+
+  $schema['semaphore'] = array(
+    'fields' => array(
+      'name' => array(
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE,
+        'default' => ''),
+      'value' => array(
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE,
+        'default' => ''),
+      'expire' => array(
+        'type' => 'float',
+        'size' => 'big',
+        'not null' => TRUE),
+      ),
+    'indexes' => array('expire' => array('expire')),
+    'primary key' => array('name'),
+  );
+  db_create_table($ret, 'semaphore', $schema['semaphore']);
+
+  return $ret;
+}
+
+/**
  * @} End of "defgroup updates-6.x-extra"
  * The next series of updates should start at 7000.
  */
Index: modules/locale/locale.module
===================================================================
--- modules/locale/locale.module	(revision 7577)
+++ modules/locale/locale.module	(working copy)
@@ -345,7 +345,7 @@
       if ($cache = cache_get('locale:'. $langcode, 'cache')) {
         $locale_t[$langcode] = $cache->data;
       }
-      else {
+      elseif (lock_acquire('locale_cache_' . $langcode)) {
         // Refresh database stored cache of translations for given language.
         // We only store short strings used in current version, to improve
         // performance and consume less memory.
@@ -354,6 +354,7 @@
           $locale_t[$langcode][$data->source] = (empty($data->translation) ? TRUE : $data->translation);
         }
         cache_set('locale:'. $langcode, $locale_t[$langcode]);
+        lock_release('locale_cache_' . $langcode);
       }
     }
   }
