Index: modules/image/image.module
===================================================================
RCS file: /cvs/drupal/drupal/modules/image/image.module,v
retrieving revision 1.43
diff -u -p -r1.43 image.module
--- modules/image/image.module	31 May 2010 11:42:11 -0000	1.43
+++ modules/image/image.module	11 Jul 2010 03:04:38 -0000
@@ -645,36 +645,34 @@ function image_style_generate() {
   // Don't start generating the image if the derivate already exists or if
   // generation is in progress in another thread.
   $lock_name = 'image_style_generate:' . $style_name . ':' . $path_hash;
-  if (!file_exists($destination)) {
-    $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();
+  $lock_acquire_attempts = 0;
+  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 < 10);
 
-  // Try to generate the image, unless another thread just did it while we were
-  // acquiring the lock.
-  $success = file_exists($destination) || image_style_create_derivative($style, $path, $destination);
+  // Either we got the lock or the file was generated by another process.
+  if ($lock_acquire_attempts < 10) {
+    $success = $file_exists || file_exists($destination) || image_style_create_derivative($style, $path, $destination);
 
-  if (!empty($lock_acquired)) {
-    lock_release($lock_name);
-  }
+    if ($lock_acquired === TRUE) {
+      lock_release($lock_name);
+    }
 
-  if ($success) {
-    $image = image_load($destination);
-    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' => $destination));
-    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();
 }
 
 /**
