Use Baton (again) in EventBase::runInEventBaseThreadAndWait
authorGiuseppe Ottaviano <ott@fb.com>
Tue, 11 Jul 2017 17:21:38 +0000 (10:21 -0700)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Tue, 11 Jul 2017 17:26:44 +0000 (10:26 -0700)
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

folly/io/async/EventBase.cpp

index 6d4a9684eaf47727e77a476d791e34b4ada93d73..11c3a601f7f7782e136a2b49486125e43114582f 100644 (file)
 #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;
 }