Index: includes/bootstrap.inc
===================================================================
--- includes/bootstrap.inc	(revision 7493)
+++ includes/bootstrap.inc	(working copy)
@@ -1054,6 +1054,8 @@ function _drupal_bootstrap($phase) {
         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,177 @@
+<?php
+// $Id$
+
+/**
+ * @file
+ * A database-mediated implementation of a locking mechanism.
+ */
+
+/**
+ * @defgroup locks Lock acquire and release functions
+ * @{
+ * Functions to coordinate long-running operations across requests.
+ *
+ * This is a cooperative, advisory lock system. Any long-running
+ * operation which could potentially be attempted in parallel by multiple
+ * requests should try to acquire a lock before proceeding.  For example,
+ * functions doing a large number of database inserts after building new
+ * data based on a drupal variable's state.  If a function fails to acquire
+ * a lock it should either immediately return, or call lock_wait() if the
+ * rest of the page request requires that the operation in question be
+ * complete.  After lock_wait() returns, the function may again attempt to
+ * acquire a 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 break stale locks, so that they do
+ * not persist.
+ *
+ * A function that has acquired a lock may attempt to renew the lock one
+ * or more times during the operation in order to extend the lifetime of the
+ * lock. 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) my be substituted
+ * by setting the 'lock_inc' variable to an alternate include filepath.
+ */
+
+/**
+ * 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;
+
+  if (isset($locks[$name])) {
+    // We acquired a lock before, so try to renew it.
+    $expire = microtime(TRUE) + $timeout;
+    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.
+    $expire = microtime(TRUE) + $timeout;
+    $retry = FALSE;
+    do {
+      if (@db_query("INSERT INTO {semaphore} (name, value, expire) VALUES ('%s', '%s', %f)", $name, _lock_id(), $expire)) {
+        $locks[$name] = TRUE;
+        $retry = FALSE;
+      }
+      else {
+        // Suppress the error, and if this is our first pass through the loop,
+        // try to break the lock in case it's expired.
+        $retry = $retry ? FALSE : lock_may_be_available($name);
+      }
+    } 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;
+  }
+  $now = microtime(TRUE);
+  if ($now > $lock['expire']) {
+    // We check two conditions to prevent a race condition where another
+    // thread acquired the lock and set a new expire time.
+    db_query("DELETE FROM {semaphore} WHERE name = '%s' AND value = '%s' AND expire = %f", $name, $lock['value'], $lock['expire']);
+    return (bool)db_affected_rows();
+  }
+  return FALSE;
+}
+
+/**
+ * Wait for a lock to be released.
+ *
+ * This will block until the lock is available, so should not be used with
+ * locks that are acquired very frequently.
+ *
+ * @param $name
+ *   The name of the lock.
+ * @param $delay
+ *   The maximum number of seconds to wait.
+ * @return TRUE if the lock holds, FALSE if it is available.
+ */
+function lock_wait($name, $delay = 30) {
+
+  while ($delay--) {
+    sleep(1);
+    if (lock_may_be_available($name)) {
+      return FALSE;
+    }
+  }
+  return TRUE;
+}
+
+/**
+ * Release a lock previously acquired by lock_acquire().
+ *
+ * @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 7493)
+++ includes/menu.inc	(working copy)
@@ -1669,15 +1669,28 @@ function menu_cache_clear_all() {
  * 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 7493)
+++ modules/system/system.install	(working copy)
@@ -956,6 +956,31 @@ function system_schema() {
     '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 @@ function system_update_6051() {
 }
 
 /**
+ * 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 7493)
+++ modules/locale/locale.module	(working copy)
@@ -345,7 +345,7 @@ function locale($string = NULL, $langcod
       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 @@ function locale($string = NULL, $langcod
           $locale_t[$langcode][$data->source] = (empty($data->translation) ? TRUE : $data->translation);
         }
         cache_set('locale:'. $langcode, $locale_t[$langcode]);
+        lock_release('locale_cache_' . $langcode);
       }
     }
   }
