lock_guard.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef _LIBCPP___MUTEX_LOCK_GUARD_H
  9. #define _LIBCPP___MUTEX_LOCK_GUARD_H
  10. #include <__config>
  11. #include <__mutex/tag_types.h>
  12. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  13. # pragma GCC system_header
  14. #endif
  15. #ifndef _LIBCPP_HAS_NO_THREADS
  16. _LIBCPP_BEGIN_NAMESPACE_STD
  17. template <class _Mutex>
  18. class _LIBCPP_TEMPLATE_VIS _LIBCPP_THREAD_SAFETY_ANNOTATION(scoped_lockable) lock_guard {
  19. public:
  20. typedef _Mutex mutex_type;
  21. private:
  22. mutex_type& __m_;
  23. public:
  24. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI explicit lock_guard(mutex_type& __m)
  25. _LIBCPP_THREAD_SAFETY_ANNOTATION(acquire_capability(__m))
  26. : __m_(__m) {
  27. __m_.lock();
  28. }
  29. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI lock_guard(mutex_type& __m, adopt_lock_t)
  30. _LIBCPP_THREAD_SAFETY_ANNOTATION(requires_capability(__m))
  31. : __m_(__m) {}
  32. _LIBCPP_HIDE_FROM_ABI ~lock_guard() _LIBCPP_THREAD_SAFETY_ANNOTATION(release_capability()) { __m_.unlock(); }
  33. private:
  34. lock_guard(lock_guard const&) = delete;
  35. lock_guard& operator=(lock_guard const&) = delete;
  36. };
  37. _LIBCPP_CTAD_SUPPORTED_FOR_TYPE(lock_guard);
  38. _LIBCPP_END_NAMESPACE_STD
  39. #endif // _LIBCPP_HAS_NO_THREADS
  40. #endif // _LIBCPP___MUTEX_LOCK_GUARD_H