Simplify the SmartMutex implementation a bit.
[oota-llvm.git] / include / llvm / System / Mutex.h
index 4f3849341aa1f45db5cb4424c6468151db3009df..d8a18865f68054529fa05b80ddd9b8ea9f41f618 100644 (file)
 #ifndef LLVM_SYSTEM_MUTEX_H
 #define LLVM_SYSTEM_MUTEX_H
 
+#include "llvm/System/Threading.h"
+
 namespace llvm
 {
   namespace sys
   {
     /// @brief Platform agnostic Mutex class.
-    class Mutex
+    class MutexImpl
     {
     /// @name Constructors
     /// @{
@@ -30,11 +32,11 @@ namespace llvm
       /// also more likely to deadlock (same thread can't acquire more than
       /// once).
       /// @brief Default Constructor.
-      explicit Mutex(bool recursive = true);
+      explicit MutexImpl(bool recursive = true);
 
       /// Releases and removes the lock
       /// @brief Destructor
-      ~Mutex();
+      ~MutexImpl();
 
     /// @}
     /// @name Methods
@@ -74,10 +76,45 @@ namespace llvm
     /// @name Do Not Implement
     /// @{
     private:
-      Mutex(const Mutex & original);
-      void operator=(const Mutex &);
+      MutexImpl(const MutexImpl & original);
+      void operator=(const MutexImpl &);
     /// @}
     };
+    
+    
+    /// SmartMutex - A mutex with a compile time constant parameter that 
+    /// indicates whether this mutex should become a no-op when we're not
+    /// running in multithreaded mode.
+    template<bool mt_only>
+    class SmartMutex : public MutexImpl {
+    public:
+      explicit SmartMutex(bool recursive = true) : MutexImpl(recursive) { }
+      
+      bool acquire() {
+        if (!mt_only && llvm_is_multithreaded())
+          return MutexImpl::acquire();
+        return true;
+      }
+
+      bool release() {
+        if (!mt_only || llvm_is_multithreaded())
+          return MutexImpl::release();
+        return true;
+      }
+
+      bool tryacquire() {
+        if (!mt_only || llvm_is_multithreaded())
+          return MutexImpl::tryacquire();
+        return true;
+      }
+      
+      private:
+        SmartMutex(const SmartMutex<mt_only> & original);
+        void operator=(const SmartMutex<mt_only> &);
+    };
+    
+    /// Mutex - A standard, always enforced mutex.
+    typedef SmartMutex<false> Mutex;
   }
 }