Bug 1363266 - Post an event to main thread to set |done| to true. draft
authorHenry Chang <hchang@mozilla.com>
Tue, 09 May 2017 11:42:52 +0800
changeset 574622 e0aab4a2bb188eabef84096b2f89cd0039eef7db
parent 572528 06d436f9330d2e8c7a7d1066f560c8a872c9eb57
child 627658 686e2fc3c350aa153fdf28ec9e3a044e3a53d012
push id57774
push userhchang@mozilla.com
push dateTue, 09 May 2017 06:04:46 +0000
bugs1363266, 1359490
milestone55.0a1
Bug 1363266 - Post an event to main thread to set |done| to true. This is in preparation for being able to be replaced with SpinEventLoopUntil(), which is going to be shipped in bug 1359490. MozReview-Commit-ID: AChVqh4kfVb
toolkit/components/url-classifier/tests/gtest/Common.cpp
--- a/toolkit/components/url-classifier/tests/gtest/Common.cpp
+++ b/toolkit/components/url-classifier/tests/gtest/Common.cpp
@@ -25,21 +25,26 @@ void RunTestInNewThread(Function&& aFunc
 
 nsresult SyncApplyUpdates(Classifier* aClassifier,
                           nsTArray<TableUpdate*>* aUpdates)
 {
   // We need to spin a new thread specifically because the callback
   // will be on the caller thread. If we call Classifier::AsyncApplyUpdates
   // and wait on the same thread, this function will never return.
 
-  nsresult ret;
+  nsresult ret = NS_ERROR_FAILURE;
   bool done = false;
   auto onUpdateComplete = [&done, &ret](nsresult rv) {
-    ret = rv;
-    done = true;
+    // We are on the "ApplyUpdate" thread. Post an event to main thread
+    // so that we can avoid busy waiting on the main thread.
+    nsCOMPtr<nsIRunnable> r = NS_NewRunnableFunction([&done, &ret, rv] {
+      ret = rv;
+      done = true;
+    });
+    NS_DispatchToMainThread(r);
   };
 
   nsCOMPtr<nsIRunnable> r = NS_NewRunnableFunction([&]() {
     nsresult rv = aClassifier->AsyncApplyUpdates(aUpdates, onUpdateComplete);
     if (NS_FAILED(rv)) {
       onUpdateComplete(rv);
     }
   });
@@ -55,19 +60,17 @@ nsresult SyncApplyUpdates(Classifier* aC
     // NS_NewCheckSummedOutputStream in HashStore::WriteFile
     // will synchronously init NS_CRYPTO_HASH_CONTRACTID on
     // the main thread. As a result we have to keep processing
     // pending event until |done| becomes true. If there's no
     // more pending event, what we only can do is wait.
     // Condition variable doesn't work here because instrusively
     // notifying the from NS_NewCheckSummedOutputStream() or
     // HashStore::WriteFile() is weird.
-    if (!NS_ProcessNextEvent(NS_GetCurrentThread(), false)) {
-      PR_Sleep(PR_MillisecondsToInterval(100));
-    }
+    MOZ_ALWAYS_TRUE(NS_ProcessNextEvent(NS_GetCurrentThread(), true));
   }
 
   return ret;
 }
 
 already_AddRefed<nsIFile>
 GetFile(const nsTArray<nsString>& path)
 {