ThreadedRepeatingFunctionRunner.h 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. /*
  2. * Copyright 2014-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 <folly/Function.h>
  18. #include <condition_variable>
  19. #include <thread>
  20. #include <vector>
  21. namespace folly {
  22. /**
  23. * For each function `fn` you add to this object, `fn` will be run in a loop
  24. * in its own thread, with the thread sleeping between invocations of `fn`
  25. * for the duration returned by `fn`'s previous run.
  26. *
  27. * To clean up these threads, invoke `stop()`, which will interrupt sleeping
  28. * threads. `stop()` will wait for already-running functions to return.
  29. *
  30. * == Alternatives ==
  31. *
  32. * If you want to multiplex multiple functions on the same thread, you can
  33. * either use EventBase with AsyncTimeout objects, or FunctionScheduler for
  34. * a slightly simpler API.
  35. *
  36. * == Thread-safety ==
  37. *
  38. * This type follows the common rule that:
  39. * (1) const member functions are safe to call concurrently with const
  40. * member functions, but
  41. * (2) non-const member functions are not safe to call concurrently with
  42. * any member functions.
  43. *
  44. * == Pitfalls ==
  45. *
  46. * Threads and classes don't mix well in C++, so you have to be very careful
  47. * if you want to have ThreadedRepeatingFunctionRunner as a member of your
  48. * class. A reasonable pattern looks like this:
  49. *
  50. * // Your class must be `final` because inheriting from a class with
  51. * // threads can cause all sorts of subtle issues:
  52. * // - Your base class might start threads that attempt to access derived
  53. * // class state **before** that state was constructed.
  54. * // - Your base class's destructor will only be able to stop threads
  55. * // **after** the derived class state was destroyed -- and that state
  56. * // might be accessed by the threads.
  57. * // In short, any derived class would have to do work to manage the
  58. * // threads itself, which makes inheritance a poor means of composition.
  59. * struct MyClass final {
  60. * // Note that threads are NOT added in the constructor, for two reasons:
  61. * //
  62. * // (1) If you first added some threads, and then had additional
  63. * // initialization (e.g. derived class constructors), `this` might
  64. * // not be fully constructed by the time the function threads
  65. * // started running, causing heisenbugs.
  66. * //
  67. * // (2) If your constructor threw after thread creation, the class
  68. * // destructor would not be invoked, potentially leaving the
  69. * // threads running too long.
  70. * //
  71. * // It is much safer to have explicit two-step initialization, or to
  72. * // lazily add threads the first time they are needed.
  73. * MyClass() : count_(0) {}
  74. *
  75. * // You must stop the threads as early as possible in the destruction
  76. * // process (or even before). If MyClass had derived classes, the final
  77. * // derived class MUST always call stop() as the first thing in its
  78. * // destructor -- otherwise, the worker threads might access already-
  79. * // destroyed state.
  80. * ~MyClass() {
  81. * threads_.stop(); // Stop threads BEFORE destroying any state they use.
  82. * }
  83. *
  84. * // See the constructor for why two-stage initialization is preferred.
  85. * void init() {
  86. * threads_.add(bind(&MyClass::incrementCount, this));
  87. * }
  88. *
  89. * std::chrono::milliseconds incrementCount() {
  90. * ++count_;
  91. * return 10;
  92. * }
  93. *
  94. * private:
  95. * std::atomic<int> count_;
  96. * // CAUTION: Declare last since the threads access other members of `this`.
  97. * ThreadedRepeatingFunctionRunner threads_;
  98. * };
  99. */
  100. class ThreadedRepeatingFunctionRunner final {
  101. public:
  102. // Returns how long to wait before the next repetition. Must not throw.
  103. using RepeatingFn = folly::Function<std::chrono::milliseconds() noexcept>;
  104. ThreadedRepeatingFunctionRunner();
  105. ~ThreadedRepeatingFunctionRunner();
  106. /**
  107. * Ideally, you will call this before initiating the destruction of the
  108. * host object. Otherwise, this should be the first thing in the
  109. * destruction sequence. If it comes any later, worker threads may access
  110. * class state that had already been destroyed.
  111. */
  112. void stop();
  113. /**
  114. * Run your noexcept function `f` in a background loop, sleeping between
  115. * calls for a duration returned by `f`. Optionally waits for
  116. * `initialSleep` before calling `f` for the first time. Names the thread
  117. * using up to the first 15 chars of `name`.
  118. *
  119. * DANGER: If a non-final class has a ThreadedRepeatingFunctionRunner
  120. * member (which, by the way, must be declared last in the class), then
  121. * you must not call add() in your constructor. Otherwise, your thread
  122. * risks accessing uninitialized data belonging to a child class. To
  123. * avoid this design bug, prefer to use two-stage initialization to start
  124. * your threads.
  125. */
  126. void add(
  127. std::string name,
  128. RepeatingFn f,
  129. std::chrono::milliseconds initialSleep = std::chrono::milliseconds(0));
  130. size_t size() const {
  131. return threads_.size();
  132. }
  133. private:
  134. // Returns true if this is the first stop().
  135. bool stopImpl();
  136. // Sleep for a duration, or until stop() is called.
  137. bool waitFor(std::chrono::milliseconds duration) noexcept;
  138. // Noexcept allows us to get a good backtrace on crashes -- otherwise,
  139. // std::terminate would get called **outside** of the thread function.
  140. void executeInLoop(
  141. RepeatingFn,
  142. std::chrono::milliseconds initialSleep) noexcept;
  143. std::mutex stopMutex_;
  144. bool stopping_{false}; // protected by stopMutex_
  145. std::condition_variable stopCv_;
  146. std::vector<std::thread> threads_;
  147. };
  148. } // namespace folly