Locked.hpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* Copyright 2025, Ableton AG, Berlin. All rights reserved.
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. *
  16. * If you would like to incorporate Link into a proprietary software application,
  17. * please contact <link-devs@ableton.com>.
  18. */
  19. #pragma once
  20. #include <mutex>
  21. namespace ableton
  22. {
  23. namespace util
  24. {
  25. template <typename T>
  26. struct Locked
  27. {
  28. public:
  29. Locked(const T& val)
  30. : mVal(val)
  31. {
  32. }
  33. T read() const
  34. {
  35. std::lock_guard lock(mMutex);
  36. return mVal;
  37. }
  38. template <typename Handler>
  39. void update(Handler handler)
  40. {
  41. std::lock_guard lock(mMutex);
  42. handler(mVal);
  43. }
  44. private:
  45. T mVal;
  46. mutable std::mutex mMutex;
  47. };
  48. } // namespace util
  49. } // namespace ableton