ScopedEventBaseThread.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright 2015-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <folly/io/async/ScopedEventBaseThread.h>
  17. #include <thread>
  18. #include <folly/Function.h>
  19. #include <folly/Range.h>
  20. #include <folly/io/async/EventBaseManager.h>
  21. #include <folly/system/ThreadName.h>
  22. using namespace std;
  23. namespace folly {
  24. static void run(
  25. EventBaseManager* ebm,
  26. EventBase* eb,
  27. folly::Baton<>* stop,
  28. const StringPiece& name) {
  29. if (name.size()) {
  30. folly::setThreadName(name);
  31. }
  32. ebm->setEventBase(eb, false);
  33. eb->loopForever();
  34. // must destruct in io thread for on-destruction callbacks
  35. EventBase::StackFunctionLoopCallback cb([=] { ebm->clearEventBase(); });
  36. eb->runOnDestruction(&cb);
  37. // wait until terminateLoopSoon() is complete
  38. stop->wait();
  39. eb->~EventBase();
  40. }
  41. ScopedEventBaseThread::ScopedEventBaseThread()
  42. : ScopedEventBaseThread(nullptr, "") {}
  43. ScopedEventBaseThread::ScopedEventBaseThread(const StringPiece& name)
  44. : ScopedEventBaseThread(nullptr, name) {}
  45. ScopedEventBaseThread::ScopedEventBaseThread(EventBaseManager* ebm)
  46. : ScopedEventBaseThread(ebm, "") {}
  47. ScopedEventBaseThread::ScopedEventBaseThread(
  48. EventBaseManager* ebm,
  49. const StringPiece& name)
  50. : ebm_(ebm ? ebm : EventBaseManager::get()) {
  51. new (&eb_) EventBase();
  52. th_ = thread(run, ebm_, &eb_, &stop_, name);
  53. eb_.waitUntilRunning();
  54. }
  55. ScopedEventBaseThread::~ScopedEventBaseThread() {
  56. eb_.terminateLoopSoon();
  57. stop_.post();
  58. th_.join();
  59. }
  60. } // namespace folly