Use Baton (again) in EventBase::runInEventBaseThreadAndWait
[folly.git] / folly / io / async / ScopedEventBaseThread.cpp
index 25f0cba757bc59b6f735f734c44e1cc1e4792d06..1e21aad79a7c4a21f68cd7c3beb1086bbd4f74bd 100644 (file)
 #include <thread>
 
 #include <folly/Function.h>
+#include <folly/Range.h>
+#include <folly/ThreadName.h>
 #include <folly/io/async/EventBaseManager.h>
 
 using namespace std;
 
 namespace folly {
 
-static void run(EventBaseManager* ebm, EventBase* eb) {
+static void run(
+    EventBaseManager* ebm,
+    EventBase* eb,
+    folly::Baton<>* stop,
+    const StringPiece& name) {
+  if (name.size()) {
+    folly::setThreadName(name);
+  }
+
   ebm->setEventBase(eb, false);
   eb->loopForever();
 
   // must destruct in io thread for on-destruction callbacks
   EventBase::StackFunctionLoopCallback cb([=] { ebm->clearEventBase(); });
   eb->runOnDestruction(&cb);
+  // wait until terminateLoopSoon() is complete
+  stop->wait();
   eb->~EventBase();
 }
 
 ScopedEventBaseThread::ScopedEventBaseThread()
-    : ScopedEventBaseThread(nullptr) {}
+    : ScopedEventBaseThread(nullptr, "") {}
+
+ScopedEventBaseThread::ScopedEventBaseThread(const StringPiece& name)
+    : ScopedEventBaseThread(nullptr, name) {}
 
 ScopedEventBaseThread::ScopedEventBaseThread(EventBaseManager* ebm)
+    : ScopedEventBaseThread(ebm, "") {}
+
+ScopedEventBaseThread::ScopedEventBaseThread(
+    EventBaseManager* ebm,
+    const StringPiece& name)
     : ebm_(ebm ? ebm : EventBaseManager::get()) {
   new (&eb_) EventBase();
-  th_ = thread(run, ebm_, &eb_);
+  th_ = thread(run, ebm_, &eb_, &stop_, name);
   eb_.waitUntilRunning();
 }
 
 ScopedEventBaseThread::~ScopedEventBaseThread() {
   eb_.terminateLoopSoon();
+  stop_.post();
   th_.join();
 }