Equalizer
1.2.1
|
00001 00002 /* Copyright (c) 2006-2011, Stefan Eilemann <eile@equalizergraphics.com> 00003 * 00004 * This library is free software; you can redistribute it and/or modify it under 00005 * the terms of the GNU Lesser General Public License version 2.1 as published 00006 * by the Free Software Foundation. 00007 * 00008 * This library is distributed in the hope that it will be useful, but WITHOUT 00009 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 00010 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more 00011 * details. 00012 * 00013 * You should have received a copy of the GNU Lesser General Public License 00014 * along with this library; if not, write to the Free Software Foundation, Inc., 00015 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 00016 */ 00017 00018 #ifndef COBASE_SCOPEDMUTEX_H 00019 #define COBASE_SCOPEDMUTEX_H 00020 00021 #include <co/base/lock.h> // used in inline method 00022 #include <co/base/lockable.h> // used in inline method 00023 #include <co/base/nonCopyable.h> // base class 00024 #include <co/base/types.h> 00025 00026 namespace co 00027 { 00028 namespace base 00029 { 00030 class WriteOp; 00031 class ReadOp; 00032 00034 template< class L, class T > struct ScopedMutexLocker {}; 00035 template< class L > struct ScopedMutexLocker< L, WriteOp > 00036 { 00037 static inline void set( L& lock ) { lock.set(); } 00038 static inline void unset( L& lock ) { lock.unset(); } 00039 }; 00040 template< class L > struct ScopedMutexLocker< L, ReadOp > 00041 { 00042 static inline void set( L& lock ) { lock.setRead(); } 00043 static inline void unset( L& lock ) { lock.unsetRead(); } 00044 }; 00054 template< class L = Lock, class T = WriteOp > 00055 class ScopedMutex : public NonCopyable 00056 { 00057 typedef ScopedMutexLocker< L, T > LockTraits; 00058 00059 public: 00069 explicit ScopedMutex( L* lock ) : _lock( lock ) 00070 { if( lock ) LockTraits::set( *lock ); } 00071 00073 explicit ScopedMutex( L& lock ) : _lock( &lock ) 00074 { LockTraits::set( lock ); } 00075 00080 template< typename LB > ScopedMutex( LB& lockable ) 00081 : _lock( &lockable.lock ) { LockTraits::set( lockable.lock ); } 00082 00084 ~ScopedMutex() { leave(); } 00085 00087 void leave() { if( _lock ) LockTraits::unset( *_lock ); _lock = 0; } 00088 00089 private: 00090 ScopedMutex(); 00091 L* _lock; 00092 }; 00093 00095 typedef ScopedMutex< SpinLock, ReadOp > ScopedFastRead; 00096 00098 typedef ScopedMutex< SpinLock, WriteOp > ScopedFastWrite; 00099 00101 typedef ScopedMutex< Lock, ReadOp > ScopedRead; 00102 00104 typedef ScopedMutex< Lock, WriteOp > ScopedWrite; 00105 } 00106 } 00107 #endif //COBASE_SCOPEDMUTEX_H