LeftRight.h 7.0 KB

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