LLVM API Documentation

MutexGuard.h
Go to the documentation of this file.
00001 //===-- Support/MutexGuard.h - Acquire/Release Mutex In Scope ---*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines a guard for a block of code that ensures a Mutex is locked
00011 // upon construction and released upon destruction.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_SUPPORT_MUTEXGUARD_H
00016 #define LLVM_SUPPORT_MUTEXGUARD_H
00017 
00018 #include "llvm/Support/Mutex.h"
00019 
00020 namespace llvm {
00021   /// Instances of this class acquire a given Mutex Lock when constructed and
00022   /// hold that lock until destruction. The intention is to instantiate one of
00023   /// these on the stack at the top of some scope to be assured that C++
00024   /// destruction of the object will always release the Mutex and thus avoid
00025   /// a host of nasty multi-threading problems in the face of exceptions, etc.
00026   /// @brief Guard a section of code with a Mutex.
00027   class MutexGuard {
00028     sys::Mutex &M;
00029     MutexGuard(const MutexGuard &) LLVM_DELETED_FUNCTION;
00030     void operator=(const MutexGuard &) LLVM_DELETED_FUNCTION;
00031   public:
00032     MutexGuard(sys::Mutex &m) : M(m) { M.lock(); }
00033     ~MutexGuard() { M.unlock(); }
00034     /// holds - Returns true if this locker instance holds the specified lock.
00035     /// This is mostly used in assertions to validate that the correct mutex
00036     /// is held.
00037     bool holds(const sys::Mutex& lock) const { return &M == &lock; }
00038   };
00039 }
00040 
00041 #endif // LLVM_SUPPORT_MUTEXGUARD_H