#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, const StringPiece& name) {
+ if (name.size()) {
+ folly::setThreadName(name);
+ }
+
ebm->setEventBase(eb, false);
eb->loopForever();
}
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_, name);
eb_.waitUntilRunning();
}
namespace folly {
class EventBaseManager;
+template <class Iter>
+class Range;
+typedef Range<const char*> StringPiece;
/**
* A helper class to start a new thread running a EventBase loop.
class ScopedEventBaseThread {
public:
ScopedEventBaseThread();
+ explicit ScopedEventBaseThread(const StringPiece& name);
explicit ScopedEventBaseThread(EventBaseManager* ebm);
+ explicit ScopedEventBaseThread(
+ EventBaseManager* ebm,
+ const StringPiece& name);
~ScopedEventBaseThread();
EventBase* getEventBase() const {
#include <folly/io/async/ScopedEventBaseThread.h>
#include <chrono>
+#include <string>
#include <folly/Baton.h>
#include <folly/Optional.h>
+#include <folly/ThreadName.h>
#include <folly/io/async/EventBaseManager.h>
#include <folly/portability/GTest.h>
ASSERT_TRUE(done.timed_wait(seconds(1)));
}
+TEST_F(ScopedEventBaseThreadTest, named_example) {
+ static constexpr StringPiece kThreadName{"named_example"};
+
+ Optional<std::string> createdThreadName;
+ Baton<> done;
+
+ ScopedEventBaseThread sebt{kThreadName};
+ sebt.getEventBase()->runInEventBaseThread([&] {
+ createdThreadName = folly::getCurrentThreadName();
+ done.post();
+ });
+
+ ASSERT_TRUE(done.timed_wait(seconds(1)));
+ if (createdThreadName) {
+ ASSERT_EQ(kThreadName.toString(), createdThreadName.value());
+ }
+}
+
TEST_F(ScopedEventBaseThreadTest, default_manager) {
auto ebm = EventBaseManager::get();
ScopedEventBaseThread sebt;