1 //===-- Support/MutexGuard.h - Acquire/Release Mutex In Scope ---*- C++ -*-===// 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 // 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_MUTEXGUARD_H 15 #define LLVM_SUPPORT_MUTEXGUARD_H 16 17 #include "llvm/Support/Mutex.h" 18 19 namespace llvm { 20 /// Instances of this class acquire a given Mutex Lock when constructed and 21 /// hold that lock until destruction. The intention is to instantiate one of 22 /// these on the stack at the top of some scope to be assured that C++ 23 /// destruction of the object will always release the Mutex and thus avoid 24 /// a host of nasty multi-threading problems in the face of exceptions, etc. 25 /// Guard a section of code with a Mutex. 26 class MutexGuard { 27 sys::Mutex &M; 28 MutexGuard(const MutexGuard &) = delete; 29 void operator=(const MutexGuard &) = delete; 30 public: MutexGuard(sys::Mutex & m)31 MutexGuard(sys::Mutex &m) : M(m) { M.lock(); } ~MutexGuard()32 ~MutexGuard() { M.unlock(); } 33 /// holds - Returns true if this locker instance holds the specified lock. 34 /// This is mostly used in assertions to validate that the correct mutex 35 /// is held. holds(const sys::Mutex & lock)36 bool holds(const sys::Mutex& lock) const { return &M == &lock; } 37 }; 38 } 39 40 #endif // LLVM_SUPPORT_MUTEXGUARD_H 41