From: Giuseppe Ottaviano <ott@fb.com>
Date: Tue, 11 Jul 2017 17:21:38 +0000 (-0700)
Subject: Use Baton (again) in EventBase::runInEventBaseThreadAndWait
X-Git-Tag: v2017.07.17.00~25
X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=6e9044430269068cc997e4077a366b5a1628c3af;p=folly.git

Use Baton (again) in EventBase::runInEventBaseThreadAndWait

Summary:
`Baton` is more lightweight than a mutex+condition variable, and the code is much simpler. This was actually the original implementation, but the dependency had to be dropped because `Baton` was unsupported on some architectures. That is not a problem anymore.

Also reorganize the includes to follow the conventions.

Reviewed By: andriigrynenko, yfeldblum

Differential Revision: D5396631

fbshipit-source-id: d782cf271eb35723aaeb3c372e1c1dafeaaf0f0a
---

diff --git a/folly/io/async/EventBase.cpp b/folly/io/async/EventBase.cpp
index 6d4a9684..11c3a601 100644
--- a/folly/io/async/EventBase.cpp
+++ b/folly/io/async/EventBase.cpp
@@ -19,18 +19,19 @@
 #endif
 
 #include <folly/io/async/EventBase.h>
-#include <folly/io/async/VirtualEventBase.h>
 
+#include <fcntl.h>
+
+#include <mutex>
+#include <thread>
+
+#include <folly/Baton.h>
 #include <folly/Memory.h>
 #include <folly/ThreadName.h>
 #include <folly/io/async/NotificationQueue.h>
+#include <folly/io/async/VirtualEventBase.h>
 #include <folly/portability/Unistd.h>
 
-#include <condition_variable>
-#include <fcntl.h>
-#include <mutex>
-#include <thread>
-
 namespace folly {
 
 /*
@@ -572,22 +573,14 @@ bool EventBase::runInEventBaseThreadAndWait(FuncRef fn) {
     return false;
   }
 
-  bool ready = false;
-  std::mutex m;
-  std::condition_variable cv;
+  Baton<> ready;
   runInEventBaseThread([&] {
-      SCOPE_EXIT {
-        std::unique_lock<std::mutex> l(m);
-        ready = true;
-        cv.notify_one();
-        // We cannot release the lock before notify_one, because a spurious
-        // wakeup in the waiting thread may lead to cv and m going out of scope
-        // prematurely.
-      };
-      fn();
+    SCOPE_EXIT {
+      ready.post();
+    };
+    fn();
   });
-  std::unique_lock<std::mutex> l(m);
-  cv.wait(l, [&] { return ready; });
+  ready.wait();
 
   return true;
 }