Synchronized.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
  2. #pragma once
  3. #include <mutex>
  4. namespace c10 {
  5. /**
  6. * A very simple Synchronization class for error-free use of data
  7. * in a multi-threaded context. See folly/docs/Synchronized.md for
  8. * the inspiration of this class.
  9. *
  10. * Full URL:
  11. * https://github.com/facebook/folly/blob/main/folly/docs/Synchronized.md
  12. *
  13. * This class implements a small subset of the generic functionality
  14. * implemented by folly:Synchronized<T>. Specifically, only withLock<T>
  15. * is implemented here since it's the smallest possible API that is
  16. * able to cover a large surface area of functionality offered by
  17. * folly::Synchronized<T>.
  18. */
  19. template <typename T>
  20. class Synchronized final {
  21. mutable std::mutex mutex_;
  22. T data_;
  23. public:
  24. Synchronized() = default;
  25. Synchronized(T const& data) : data_(data) {}
  26. Synchronized(T&& data) : data_(std::move(data)) {}
  27. // Don't permit copy construction, move, assignment, or
  28. // move assignment, since the underlying std::mutex
  29. // isn't necessarily copyable/moveable.
  30. Synchronized(Synchronized const&) = delete;
  31. Synchronized(Synchronized&&) = delete;
  32. Synchronized operator=(Synchronized const&) = delete;
  33. Synchronized operator=(Synchronized&&) = delete;
  34. ~Synchronized() = default;
  35. /**
  36. * To use, call withLock<T> with a callback that accepts T either
  37. * by copy or by reference. Use the protected variable in the
  38. * provided callback safely.
  39. */
  40. template <typename CB>
  41. auto withLock(CB&& cb) {
  42. std::lock_guard<std::mutex> guard(this->mutex_);
  43. return std::forward<CB>(cb)(this->data_);
  44. }
  45. /**
  46. * To use, call withLock<T> with a callback that accepts T either
  47. * by copy or by const reference. Use the protected variable in
  48. * the provided callback safely.
  49. */
  50. template <typename CB>
  51. auto withLock(CB&& cb) const {
  52. std::lock_guard<std::mutex> guard(this->mutex_);
  53. return std::forward<CB>(cb)(this->data_);
  54. }
  55. };
  56. } // end namespace c10
  57. #else
  58. #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
  59. #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)