Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

scoped_lock.hpp 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. //
  2. // detail/scoped_lock.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef ASIO_DETAIL_SCOPED_LOCK_HPP
  11. #define ASIO_DETAIL_SCOPED_LOCK_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include "asio/detail/noncopyable.hpp"
  16. #include "asio/detail/push_options.hpp"
  17. namespace asio {
  18. namespace detail {
  19. // Helper class to lock and unlock a mutex automatically.
  20. template <typename Mutex>
  21. class scoped_lock
  22. : private noncopyable
  23. {
  24. public:
  25. // Tag type used to distinguish constructors.
  26. enum adopt_lock_t { adopt_lock };
  27. // Constructor adopts a lock that is already held.
  28. scoped_lock(Mutex& m, adopt_lock_t)
  29. : mutex_(m),
  30. locked_(true)
  31. {
  32. }
  33. // Constructor acquires the lock.
  34. explicit scoped_lock(Mutex& m)
  35. : mutex_(m)
  36. {
  37. mutex_.lock();
  38. locked_ = true;
  39. }
  40. // Destructor releases the lock.
  41. ~scoped_lock()
  42. {
  43. if (locked_)
  44. mutex_.unlock();
  45. }
  46. // Explicitly acquire the lock.
  47. void lock()
  48. {
  49. if (!locked_)
  50. {
  51. mutex_.lock();
  52. locked_ = true;
  53. }
  54. }
  55. // Explicitly release the lock.
  56. void unlock()
  57. {
  58. if (locked_)
  59. {
  60. mutex_.unlock();
  61. locked_ = false;
  62. }
  63. }
  64. // Test whether the lock is held.
  65. bool locked() const
  66. {
  67. return locked_;
  68. }
  69. // Get the underlying mutex.
  70. Mutex& mutex()
  71. {
  72. return mutex_;
  73. }
  74. private:
  75. // The underlying mutex.
  76. Mutex& mutex_;
  77. // Whether the mutex is currently locked or unlocked.
  78. bool locked_;
  79. };
  80. } // namespace detail
  81. } // namespace asio
  82. #include "asio/detail/pop_options.hpp"
  83. #endif // ASIO_DETAIL_SCOPED_LOCK_HPP