UniqueLock.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //===-- Support/UniqueLock.h - Acquire/Release Mutex In Scope ---*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines a guard for a block of code that ensures a Mutex is locked
  11. // upon construction and released upon destruction.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_SUPPORT_UNIQUE_LOCK_H
  15. #define LLVM_SUPPORT_UNIQUE_LOCK_H
  16. #include "llvm/Support/Mutex.h"
  17. namespace llvm {
  18. /// A pared-down imitation of std::unique_lock from C++11. Contrary to the
  19. /// name, it's really more of a wrapper for a lock. It may or may not have
  20. /// an associated mutex, which is guaranteed to be locked upon creation
  21. /// and unlocked after destruction. unique_lock can also unlock the mutex
  22. /// and re-lock it freely during its lifetime.
  23. /// @brief Guard a section of code with a mutex.
  24. template<typename MutexT>
  25. class unique_lock {
  26. MutexT *M;
  27. bool locked;
  28. unique_lock(const unique_lock &) = delete;
  29. void operator=(const unique_lock &) = delete;
  30. public:
  31. unique_lock() : M(nullptr), locked(false) {}
  32. explicit unique_lock(MutexT &m) : M(&m), locked(true) { M->lock(); }
  33. void operator=(unique_lock &&o) {
  34. if (owns_lock())
  35. M->unlock();
  36. M = o.M;
  37. locked = o.locked;
  38. o.M = nullptr;
  39. o.locked = false;
  40. }
  41. ~unique_lock() { if (owns_lock()) M->unlock(); }
  42. void lock() {
  43. assert(!locked && "mutex already locked!");
  44. assert(M && "no associated mutex!");
  45. M->lock();
  46. locked = true;
  47. }
  48. void unlock() {
  49. assert(locked && "unlocking a mutex that isn't locked!");
  50. assert(M && "no associated mutex!");
  51. M->unlock();
  52. locked = false;
  53. }
  54. bool owns_lock() { return locked; }
  55. };
  56. }
  57. #endif // LLVM_SUPPORT_UNIQUE_LOCK_H