ScopedLock.hpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Tencent is pleased to support the open source community by making
  3. * MMKV available.
  4. *
  5. * Copyright (C) 2018 THL A29 Limited, a Tencent company.
  6. * All rights reserved.
  7. *
  8. * Licensed under the BSD 3-Clause License (the "License"); you may not use
  9. * this file except in compliance with the License. You may obtain a copy of
  10. * the License at
  11. *
  12. * https://opensource.org/licenses/BSD-3-Clause
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. #ifndef MMKV_SCOPEDLOCK_HPP
  21. #define MMKV_SCOPEDLOCK_HPP
  22. #ifdef __cplusplus
  23. namespace mmkv {
  24. template <typename T>
  25. class ScopedLock {
  26. T *m_lock;
  27. void lock() {
  28. if (m_lock) {
  29. m_lock->lock();
  30. }
  31. }
  32. void unlock() {
  33. if (m_lock) {
  34. m_lock->unlock();
  35. }
  36. }
  37. public:
  38. explicit ScopedLock(T *oLock) : m_lock(oLock) {
  39. MMKV_ASSERT(m_lock);
  40. lock();
  41. }
  42. ~ScopedLock() {
  43. unlock();
  44. m_lock = nullptr;
  45. }
  46. // just forbid it for possibly misuse
  47. explicit ScopedLock(const ScopedLock<T> &other) = delete;
  48. ScopedLock &operator=(const ScopedLock<T> &other) = delete;
  49. };
  50. } // namespace mmkv
  51. #include <type_traits>
  52. #define SCOPED_LOCK(lock) _SCOPEDLOCK(lock, __COUNTER__)
  53. #define _SCOPEDLOCK(lock, counter) __SCOPEDLOCK(lock, counter)
  54. #define __SCOPEDLOCK(lock, counter) \
  55. mmkv::ScopedLock<std::remove_pointer<decltype(lock)>::type> __scopedLock##counter(lock)
  56. #endif
  57. #endif //MMKV_SCOPEDLOCK_HPP