Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 1 | //===- Support/UniqueLock.h - Acquire/Release Mutex In Scope ----*- C++ -*-===// |
| 2 | // |
Andrew Walbran | 16937d0 | 2019-10-22 13:54:20 +0100 | [diff] [blame] | 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 |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file defines a guard for a block of code that ensures a Mutex is locked |
| 10 | // upon construction and released upon destruction. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #ifndef LLVM_SUPPORT_UNIQUE_LOCK_H |
| 15 | #define LLVM_SUPPORT_UNIQUE_LOCK_H |
| 16 | |
| 17 | #include <cassert> |
| 18 | |
| 19 | namespace llvm { |
| 20 | |
| 21 | /// A pared-down imitation of std::unique_lock from C++11. Contrary to the |
| 22 | /// name, it's really more of a wrapper for a lock. It may or may not have |
| 23 | /// an associated mutex, which is guaranteed to be locked upon creation |
| 24 | /// and unlocked after destruction. unique_lock can also unlock the mutex |
| 25 | /// and re-lock it freely during its lifetime. |
Andrew Scull | cdfcccc | 2018-10-05 20:58:37 +0100 | [diff] [blame] | 26 | /// Guard a section of code with a mutex. |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 27 | template<typename MutexT> |
| 28 | class unique_lock { |
| 29 | MutexT *M = nullptr; |
| 30 | bool locked = false; |
| 31 | |
| 32 | public: |
| 33 | unique_lock() = default; |
| 34 | explicit unique_lock(MutexT &m) : M(&m), locked(true) { M->lock(); } |
| 35 | unique_lock(const unique_lock &) = delete; |
| 36 | unique_lock &operator=(const unique_lock &) = delete; |
| 37 | |
| 38 | void operator=(unique_lock &&o) { |
| 39 | if (owns_lock()) |
| 40 | M->unlock(); |
| 41 | M = o.M; |
| 42 | locked = o.locked; |
| 43 | o.M = nullptr; |
| 44 | o.locked = false; |
| 45 | } |
| 46 | |
| 47 | ~unique_lock() { if (owns_lock()) M->unlock(); } |
| 48 | |
| 49 | void lock() { |
| 50 | assert(!locked && "mutex already locked!"); |
| 51 | assert(M && "no associated mutex!"); |
| 52 | M->lock(); |
| 53 | locked = true; |
| 54 | } |
| 55 | |
| 56 | void unlock() { |
| 57 | assert(locked && "unlocking a mutex that isn't locked!"); |
| 58 | assert(M && "no associated mutex!"); |
| 59 | M->unlock(); |
| 60 | locked = false; |
| 61 | } |
| 62 | |
| 63 | bool owns_lock() { return locked; } |
| 64 | }; |
| 65 | |
| 66 | } // end namespace llvm |
| 67 | |
| 68 | #endif // LLVM_SUPPORT_UNIQUE_LOCK_H |