Synchronized.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. ~Synchronized() = default;
  34. /**
  35. * To use, call withLock<T> with a callback that accepts T either
  36. * by copy or by reference. Use the protected variable in the
  37. * provided callback safely.
  38. */
  39. template <typename CB>
  40. auto withLock(CB&& cb) {
  41. std::lock_guard<std::mutex> guard(this->mutex_);
  42. return std::forward<CB>(cb)(this->data_);
  43. }
  44. /**
  45. * To use, call withLock<T> with a callback that accepts T either
  46. * by copy or by const reference. Use the protected variable in
  47. * the provided callback safely.
  48. */
  49. template <typename CB>
  50. auto withLock(CB&& cb) const {
  51. std::lock_guard<std::mutex> guard(this->mutex_);
  52. return std::forward<CB>(cb)(this->data_);
  53. }
  54. };
  55. } // end namespace c10