1 //===-- Support/MutexGuard.h - Acquire/Release Mutex In Scope ---*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines a guard for a block of code that ensures a Mutex is locked
10 // upon construction and released upon destruction.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_SUPPORT_MUTEXGUARD_H
15 #define LLVM_SUPPORT_MUTEXGUARD_H
17 #include "llvm/Support/Mutex.h"
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.
28 MutexGuard(const MutexGuard
&) = delete;
29 void operator=(const MutexGuard
&) = delete;
31 MutexGuard(sys::Mutex
&m
) : M(m
) { M
.lock(); }
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
36 bool holds(const sys::Mutex
& lock
) const { return &M
== &lock
; }
40 #endif // LLVM_SUPPORT_MUTEXGUARD_H