ScopedLock.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* mbed Microcontroller Library
  2. * Copyright (c) 2018 ARM Limited
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef MBED_SCOPEDLOCK_H
  17. #define MBED_SCOPEDLOCK_H
  18. #include "platform/NonCopyable.h"
  19. namespace mbed {
  20. /** \addtogroup platform */
  21. /** @{*/
  22. /**
  23. * \defgroup platform_ScopedLock ScopedLock functions
  24. * @{
  25. */
  26. /** RAII-style mechanism for owning a lock of Lockable object for the duration of a scoped block
  27. *
  28. * @tparam Lockable The type implementing BasicLockable concept
  29. *
  30. * @note For type Lockable to be BasicLockable, the following conditions have to be satisfied:
  31. * - has public member function @a lock which blocks until a lock can be obtained for the current execution context
  32. * - has public member function @a unlock which releases the lock
  33. *
  34. * Usage:
  35. *
  36. * Example with rtos::Mutex
  37. *
  38. * @code
  39. * void foo(Mutex &m) {
  40. * ScopedLock<Mutex> lock(m);
  41. * // Mutex lock protects code in this block
  42. * }
  43. * @endcode
  44. *
  45. *
  46. * More generic example
  47. *
  48. * @code
  49. * template<typename Lockable>
  50. * void foo(Lockable& lockable) {
  51. * ScopedLock<Lockable> lock(lockable);
  52. * // Code in this block runs under lock
  53. * }
  54. * @endcode
  55. */
  56. template <typename Lockable>
  57. class ScopedLock : private NonCopyable<ScopedLock<Lockable> > {
  58. public:
  59. /** Locks given locable object
  60. *
  61. * @param lockable reference to the instance of Lockable object
  62. * @note lockable object should outlive the ScopedLock object
  63. */
  64. ScopedLock(Lockable &lockable): _lockable(lockable)
  65. {
  66. _lockable.lock();
  67. }
  68. ~ScopedLock()
  69. {
  70. _lockable.unlock();
  71. }
  72. private:
  73. Lockable &_lockable;
  74. };
  75. /**@}*/
  76. /**@}*/
  77. } // embed
  78. #endif // MBED_SCOPEDLOCK_H