Lunchbox  1.8.0
scopedMutex.h
1 
2 /* Copyright (c) 2006-2012, Stefan Eilemann <eile@equalizergraphics.com>
3  *
4  * This library is free software; you can redistribute it and/or modify it under
5  * the terms of the GNU Lesser General Public License version 2.1 as published
6  * by the Free Software Foundation.
7  *
8  * This library is distributed in the hope that it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
11  * details.
12  *
13  * You should have received a copy of the GNU Lesser General Public License
14  * along with this library; if not, write to the Free Software Foundation, Inc.,
15  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16  */
17 
18 #ifndef LUNCHBOX_SCOPEDMUTEX_H
19 #define LUNCHBOX_SCOPEDMUTEX_H
20 
21 #include <lunchbox/condition.h> // used in inline method
22 #include <lunchbox/lock.h> // used in inline method
23 #include <lunchbox/lockable.h> // used in inline method
24 #include <lunchbox/types.h>
25 
26 namespace lunchbox
27 {
28  class WriteOp;
29  class ReadOp;
30 
32  template< class L, class T > struct ScopedMutexLocker {};
33  template< class L > struct ScopedMutexLocker< L, WriteOp >
34  {
35  static inline void set( L& lock ) { lock.set(); }
36  static inline void unset( L& lock ) { lock.unset(); }
37  };
38  template< class L > struct ScopedMutexLocker< L, ReadOp >
39  {
40  static inline void set( L& lock ) { lock.setRead(); }
41  static inline void unset( L& lock ) { lock.unsetRead(); }
42  };
43  template<> struct ScopedMutexLocker< Condition, WriteOp >
44  {
45  static inline void set( Condition& cond ) { cond.lock(); }
46  static inline void unset( Condition& cond ) { cond.unlock(); }
47  };
57  template< class L = Lock, class T = WriteOp >
59  {
60  typedef ScopedMutexLocker< L, T > LockTraits;
61 
62  public:
72  explicit ScopedMutex( L* lock ) : _lock( lock )
73  { if( lock ) LockTraits::set( *lock ); }
74 
76  explicit ScopedMutex( L& lock ) : _lock( &lock )
77  { LockTraits::set( lock ); }
78 
80  ScopedMutex( const ScopedMutex& rhs ) : _lock( rhs._lock )
81  { const_cast< ScopedMutex& >( rhs )._lock = 0; }
82 
85  {
86  if( this != &rhs )
87  {
88  _lock = rhs._lock;
89  rhs._lock = 0;
90  }
91  return *this;
92  }
93 
98  template< typename LB > explicit ScopedMutex( const LB& lockable )
99  : _lock( &lockable.lock ) { LockTraits::set( lockable.lock ); }
100 
103 
105  void leave() { if( _lock ) LockTraits::unset( *_lock ); _lock = 0; }
106 
107  private:
108  ScopedMutex();
109  L* _lock;
110  };
111 
114 
117 
120 
123 
126 }
127 #endif //LUNCHBOX_SCOPEDMUTEX_H