LeftRight.h 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. #include <c10/macros/Macros.h>
  2. #include <c10/util/Synchronized.h>
  3. #include <array>
  4. #include <atomic>
  5. #include <mutex>
  6. #include <thread>
  7. namespace c10 {
  8. namespace detail {
  9. struct IncrementRAII final {
  10. public:
  11. explicit IncrementRAII(std::atomic<int32_t>* counter) : _counter(counter) {
  12. _counter->fetch_add(1);
  13. }
  14. ~IncrementRAII() {
  15. _counter->fetch_sub(1);
  16. }
  17. private:
  18. std::atomic<int32_t>* _counter;
  19. C10_DISABLE_COPY_AND_ASSIGN(IncrementRAII);
  20. };
  21. } // namespace detail
  22. // LeftRight wait-free readers synchronization primitive
  23. // https://hal.archives-ouvertes.fr/hal-01207881/document
  24. //
  25. // LeftRight is quite easy to use (it can make an arbitrary
  26. // data structure permit wait-free reads), but it has some
  27. // particular performance characteristics you should be aware
  28. // of if you're deciding to use it:
  29. //
  30. // - Reads still incur an atomic write (this is how LeftRight
  31. // keeps track of how long it needs to keep around the old
  32. // data structure)
  33. //
  34. // - Writes get executed twice, to keep both the left and right
  35. // versions up to date. So if your write is expensive or
  36. // nondeterministic, this is also an inappropriate structure
  37. //
  38. // LeftRight is used fairly rarely in PyTorch's codebase. If you
  39. // are still not sure if you need it or not, consult your local
  40. // C++ expert.
  41. //
  42. template <class T>
  43. class LeftRight final {
  44. public:
  45. template <class... Args>
  46. explicit LeftRight(const Args&... args)
  47. : _counters{{{0}, {0}}},
  48. _foregroundCounterIndex(0),
  49. _foregroundDataIndex(0),
  50. _data{{T{args...}, T{args...}}},
  51. _writeMutex() {}
  52. // Copying and moving would not be threadsafe.
  53. // Needs more thought and careful design to make that work.
  54. LeftRight(const LeftRight&) = delete;
  55. LeftRight(LeftRight&&) noexcept = delete;
  56. LeftRight& operator=(const LeftRight&) = delete;
  57. LeftRight& operator=(LeftRight&&) noexcept = delete;
  58. ~LeftRight() {
  59. // wait until any potentially running writers are finished
  60. { std::unique_lock<std::mutex> lock(_writeMutex); }
  61. // wait until any potentially running readers are finished
  62. while (_counters[0].load() != 0 || _counters[1].load() != 0) {
  63. std::this_thread::yield();
  64. }
  65. }
  66. template <typename F>
  67. auto read(F&& readFunc) const {
  68. detail::IncrementRAII _increment_counter(
  69. &_counters[_foregroundCounterIndex.load()]);
  70. return std::forward<F>(readFunc)(_data[_foregroundDataIndex.load()]);
  71. }
  72. // Throwing an exception in writeFunc is ok but causes the state to be either
  73. // the old or the new state, depending on if the first or the second call to
  74. // writeFunc threw.
  75. template <typename F>
  76. auto write(F&& writeFunc) {
  77. std::unique_lock<std::mutex> lock(_writeMutex);
  78. return _write(std::forward<F>(writeFunc));
  79. }
  80. private:
  81. template <class F>
  82. auto _write(const F& writeFunc) {
  83. /*
  84. * Assume, A is in background and B in foreground. In simplified terms, we
  85. * want to do the following:
  86. * 1. Write to A (old background)
  87. * 2. Switch A/B
  88. * 3. Write to B (new background)
  89. *
  90. * More detailed algorithm (explanations on why this is important are below
  91. * in code):
  92. * 1. Write to A
  93. * 2. Switch A/B data pointers
  94. * 3. Wait until A counter is zero
  95. * 4. Switch A/B counters
  96. * 5. Wait until B counter is zero
  97. * 6. Write to B
  98. */
  99. auto localDataIndex = _foregroundDataIndex.load();
  100. // 1. Write to A
  101. _callWriteFuncOnBackgroundInstance(writeFunc, localDataIndex);
  102. // 2. Switch A/B data pointers
  103. localDataIndex = localDataIndex ^ 1;
  104. _foregroundDataIndex = localDataIndex;
  105. /*
  106. * 3. Wait until A counter is zero
  107. *
  108. * In the previous write run, A was foreground and B was background.
  109. * There was a time after switching _foregroundDataIndex (B to foreground)
  110. * and before switching _foregroundCounterIndex, in which new readers could
  111. * have read B but incremented A's counter.
  112. *
  113. * In this current run, we just switched _foregroundDataIndex (A back to
  114. * foreground), but before writing to the new background B, we have to make
  115. * sure A's counter was zero briefly, so all these old readers are gone.
  116. */
  117. auto localCounterIndex = _foregroundCounterIndex.load();
  118. _waitForBackgroundCounterToBeZero(localCounterIndex);
  119. /*
  120. * 4. Switch A/B counters
  121. *
  122. * Now that we know all readers on B are really gone, we can switch the
  123. * counters and have new readers increment A's counter again, which is the
  124. * correct counter since they're reading A.
  125. */
  126. localCounterIndex = localCounterIndex ^ 1;
  127. _foregroundCounterIndex = localCounterIndex;
  128. /*
  129. * 5. Wait until B counter is zero
  130. *
  131. * This waits for all the readers on B that came in while both data and
  132. * counter for B was in foreground, i.e. normal readers that happened
  133. * outside of that brief gap between switching data and counter.
  134. */
  135. _waitForBackgroundCounterToBeZero(localCounterIndex);
  136. // 6. Write to B
  137. return _callWriteFuncOnBackgroundInstance(writeFunc, localDataIndex);
  138. }
  139. template <class F>
  140. auto _callWriteFuncOnBackgroundInstance(
  141. const F& writeFunc,
  142. uint8_t localDataIndex) {
  143. try {
  144. return writeFunc(_data[localDataIndex ^ 1]);
  145. } catch (...) {
  146. // recover invariant by copying from the foreground instance
  147. _data[localDataIndex ^ 1] = _data[localDataIndex];
  148. // rethrow
  149. throw;
  150. }
  151. }
  152. void _waitForBackgroundCounterToBeZero(uint8_t counterIndex) {
  153. while (_counters[counterIndex ^ 1].load() != 0) {
  154. std::this_thread::yield();
  155. }
  156. }
  157. mutable std::array<std::atomic<int32_t>, 2> _counters;
  158. std::atomic<uint8_t> _foregroundCounterIndex;
  159. std::atomic<uint8_t> _foregroundDataIndex;
  160. std::array<T, 2> _data;
  161. std::mutex _writeMutex;
  162. };
  163. // RWSafeLeftRightWrapper is API compatible with LeftRight and uses a
  164. // read-write lock to protect T (data).
  165. template <class T>
  166. class RWSafeLeftRightWrapper final {
  167. public:
  168. template <class... Args>
  169. explicit RWSafeLeftRightWrapper(const Args&... args) : data_{args...} {}
  170. // RWSafeLeftRightWrapper is not copyable or moveable since LeftRight
  171. // is not copyable or moveable.
  172. RWSafeLeftRightWrapper(const RWSafeLeftRightWrapper&) = delete;
  173. RWSafeLeftRightWrapper(RWSafeLeftRightWrapper&&) noexcept = delete;
  174. RWSafeLeftRightWrapper& operator=(const RWSafeLeftRightWrapper&) = delete;
  175. RWSafeLeftRightWrapper& operator=(RWSafeLeftRightWrapper&&) noexcept = delete;
  176. template <typename F>
  177. // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
  178. auto read(F&& readFunc) const {
  179. return data_.withLock(
  180. [&readFunc](T const& data) { return std::forward<F>(readFunc)(data); });
  181. }
  182. template <typename F>
  183. // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward)
  184. auto write(F&& writeFunc) {
  185. return data_.withLock(
  186. [&writeFunc](T& data) { return std::forward<F>(writeFunc)(data); });
  187. }
  188. private:
  189. c10::Synchronized<T> data_;
  190. };
  191. } // namespace c10