Synchronized.h 1.9 KB

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