Index: modules/image/image.module
===================================================================
RCS file: /cvs/drupal/drupal/modules/image/image.module,v
retrieving revision 1.54
diff -u -p -r1.54 image.module
--- modules/image/image.module	18 Nov 2010 05:36:27 -0000	1.54
+++ modules/image/image.module	6 Jan 2011 01:02:45 -0000
@@ -680,37 +680,35 @@ function image_style_deliver($style, $sc
 
   // Don't start generating the image if the derivative already exists or if
   // generation is in progress in another thread.
+  $lock_acquire_attempts = 0;
   $lock_name = 'image_style_deliver:' . $style['name'] . ':' . drupal_hash_base64($image_uri);
-  if (!file_exists($derivative_uri)) {
-    $lock_acquired = lock_acquire($lock_name);
-    if (!$lock_acquired) {
-      // Tell client to retry again in 3 seconds. Currently no browsers are known
-      // to support Retry-After.
-      drupal_add_http_header('Status', '503 Service Unavailable');
-      drupal_add_http_header('Retry-After', 3);
-      print t('Image generation in progress. Try again shortly.');
-      drupal_exit();
+  do {
+    if (!$file_exists = file_exists($destination)) {
+      if (!$lock_acquired = lock_acquire($lock_name)) {
+        lock_wait($lock_name, 3);
+      }
     }
   }
+  while ($file_exists === FALSE && $lock_acquired === FALSE && ++$lock_acquire_attempts < 5);
 
-  // Try to generate the image, unless another thread just did it while we were
-  // acquiring the lock.
-  $success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
+  // Either we got the lock or the file was generated by another process.
+  if ($lock_acquire_attempts < 5) {
+    $success = $file_exists || file_exists($destination) || image_style_create_derivative($style, $path, $destination);
 
-  if (!empty($lock_acquired)) {
-    lock_release($lock_name);
-  }
+    if (!empty($lock_acquired)) {
+      lock_release($lock_name);
+    }
 
-  if ($success) {
-    $image = image_load($derivative_uri);
-    file_transfer($image->source, array('Content-Type' => $image->info['mime_type'], 'Content-Length' => $image->info['file_size']));
-  }
-  else {
-    watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
-    drupal_add_http_header('Status', '500 Internal Server Error');
-    print t('Error generating image.');
-    drupal_exit();
+    if ($success) {
+      $image = image_load($destination);
+      file_transfer($image->source, array('Content-Type' => $image->info['mime_type'], 'Content-Length' => $image->info['file_size']));
+    }
   }
+
+  watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $destination));
+  drupal_add_http_header('Status', '500 Internal Server Error');
+  print t('Error generating image.');
+  drupal_exit();
 }
 
 /**
