1193323Sed//===-- Support/MutexGuard.h - Acquire/Release Mutex In Scope ---*- C++ -*-===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file defines a guard for a block of code that ensures a Mutex is locked
11193323Sed// upon construction and released upon destruction.
12193323Sed//
13193323Sed//===----------------------------------------------------------------------===//
14193323Sed
15193323Sed#ifndef LLVM_SUPPORT_MUTEXGUARD_H
16193323Sed#define LLVM_SUPPORT_MUTEXGUARD_H
17193323Sed
18218893Sdim#include "llvm/Support/Mutex.h"
19193323Sed
20193323Sednamespace llvm {
21193323Sed  /// Instances of this class acquire a given Mutex Lock when constructed and
22193323Sed  /// hold that lock until destruction. The intention is to instantiate one of
23193323Sed  /// these on the stack at the top of some scope to be assured that C++
24193323Sed  /// destruction of the object will always release the Mutex and thus avoid
25193323Sed  /// a host of nasty multi-threading problems in the face of exceptions, etc.
26193323Sed  /// @brief Guard a section of code with a Mutex.
27193323Sed  class MutexGuard {
28193323Sed    sys::Mutex &M;
29245431Sdim    MutexGuard(const MutexGuard &) LLVM_DELETED_FUNCTION;
30245431Sdim    void operator=(const MutexGuard &) LLVM_DELETED_FUNCTION;
31193323Sed  public:
32193323Sed    MutexGuard(sys::Mutex &m) : M(m) { M.acquire(); }
33193323Sed    ~MutexGuard() { M.release(); }
34193323Sed    /// holds - Returns true if this locker instance holds the specified lock.
35193323Sed    /// This is mostly used in assertions to validate that the correct mutex
36193323Sed    /// is held.
37193323Sed    bool holds(const sys::Mutex& lock) const { return &M == &lock; }
38193323Sed  };
39193323Sed}
40193323Sed
41193323Sed#endif // LLVM_SUPPORT_MUTEXGUARD_H
42