libcommonc++  0.7
ScopedLock.h++
Go to the documentation of this file.
1 /* ---------------------------------------------------------------------------
2  commonc++ - A C++ Common Class Library
3  Copyright (C) 2005-2014 Mark A Lindner
4 
5  This file is part of commonc++.
6 
7  This library is free software; you can redistribute it and/or
8  modify it under the terms of the GNU Library General Public
9  License as published by the Free Software Foundation; either
10  version 2 of the License, or (at your option) any later version.
11 
12  This library is distributed in the hope that it will be useful,
13  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  Library General Public License for more details.
16 
17  You should have received a copy of the GNU Library General Public
18  License along with this library; if not, write to the Free
19  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  ---------------------------------------------------------------------------
21 */
22 
23 #ifndef __ccxx_ScopedLock_hxx
24 #define __ccxx_ScopedLock_hxx
25 
26 #include <commonc++/Common.h++>
27 #include <commonc++/Lock.h++>
28 
29 namespace ccxx {
30 
50 class /* COMMONCPP_API */ ScopedLock
51 {
52  public:
53 
59  : _lock(lock),
60  _once(true)
61  {
62  _lock.lock();
63  }
64 
67  {
68  _lock.unlock();
69  }
70 
72  inline bool testOnce()
73  { bool f = _once; _once = false; return(f); }
76  private:
77 
78  Lock& _lock;
79  bool _once;
80 
81  CCXX_COPY_DECLS(ScopedLock);
82 };
83 
84 } // namespace ccxx
85 
90 #ifdef synchronized
91 #undef synchronized
92 #endif
93 
94 #if (defined CCXX_OS_WINDOWS) && (defined _MSC_VER) && (_MSC_VER < 1400)
95 
96 #define synchronized(LOCK) \
97  for(ccxx::ScopedLock LOCK ## _locker(LOCK); \
98  LOCK ## _locker.testOnce();)
99 
100 #else
101 
102 #define synchronized(LOCK) \
103  for(ccxx::ScopedLock \
104  CCXX_UNIQUE_VARNAME(LOCK, __LINE__, locker)(LOCK); \
105  CCXX_UNIQUE_VARNAME(LOCK, __LINE__, locker).testOnce();)
106 
107 #endif
108 
109 #endif // __ccxx_ScopedLock_hxx
virtual void unlock()=0
Unlock operation.
A convenience object for lexical scope based synchronization.
Definition: ScopedLock.h++:50
An abstract base class for synchronization primitives.
Definition: Lock.h++:35
ScopedLock(Lock &lock)
Construct a new Scopedock for the given Lock.
Definition: ScopedLock.h++:58
~ScopedLock()
Destructor.
Definition: ScopedLock.h++:66
virtual void lock()=0
Lock operation.
Definition: AllocationMap.c++:25