ScopedEventBaseThread.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. #pragma once
  17. #include <memory>
  18. #include <thread>
  19. #include <folly/io/async/EventBase.h>
  20. #include <folly/synchronization/Baton.h>
  21. namespace folly {
  22. class EventBaseManager;
  23. template <class Iter>
  24. class Range;
  25. typedef Range<const char*> StringPiece;
  26. /**
  27. * A helper class to start a new thread running a EventBase loop.
  28. *
  29. * The new thread will be started by the ScopedEventBaseThread constructor.
  30. * When the ScopedEventBaseThread object is destroyed, the thread will be
  31. * stopped.
  32. */
  33. class ScopedEventBaseThread : public IOExecutor, public SequencedExecutor {
  34. public:
  35. ScopedEventBaseThread();
  36. explicit ScopedEventBaseThread(const StringPiece& name);
  37. explicit ScopedEventBaseThread(EventBaseManager* ebm);
  38. explicit ScopedEventBaseThread(
  39. EventBaseManager* ebm,
  40. const StringPiece& name);
  41. ~ScopedEventBaseThread();
  42. EventBase* getEventBase() const {
  43. return &eb_;
  44. }
  45. EventBase* getEventBase() override {
  46. return &eb_;
  47. }
  48. std::thread::id getThreadId() const {
  49. return th_.get_id();
  50. }
  51. void add(Func func) override {
  52. getEventBase()->add(std::move(func));
  53. }
  54. private:
  55. ScopedEventBaseThread(ScopedEventBaseThread&& other) = delete;
  56. ScopedEventBaseThread& operator=(ScopedEventBaseThread&& other) = delete;
  57. ScopedEventBaseThread(const ScopedEventBaseThread& other) = delete;
  58. ScopedEventBaseThread& operator=(const ScopedEventBaseThread& other) = delete;
  59. EventBaseManager* ebm_;
  60. union {
  61. mutable EventBase eb_;
  62. };
  63. std::thread th_;
  64. folly::Baton<> stop_;
  65. };
  66. } // namespace folly