1
////////////////////////////////////////////////////////////////////////////////
3
// Copyright (c) 2001 by Andrei Alexandrescu
4
// This code is from the article:
5
// "Generic<Programming>: volatile � Multithreaded Programmer�s Best Friend
6
// Volatile-Correctness or How to Have Your Compiler Detect Race Conditions
7
// for You" by Alexandrescu, Andrei.
8
// Published in the February 2001 issue of the C/C++ Users Journal.
9
// http://www.cuj.com/documents/s=7998/cujcexp1902alexandr/
10
// Prepared for Loki library by Richard Sposato
11
////////////////////////////////////////////////////////////////////////////////
12
#ifndef LOKI_LOCKING_PTR_INC_
13
#define LOKI_LOCKING_PTR_INC_
15
// $Id: LockingPtr.h 748 2006-10-17 19:49:08Z syntheticpp $
18
#include <loki/ConstPolicy.h>
23
Locks a volatile object and casts away volatility so that the object
24
can be safely used in a single-threaded region of code.
25
Original version of LockingPtr had only one template - for the shared
26
object, but not the mutex type. This version allows users to specify a
27
the mutex type as a LockingPolicy class. The only requirements for a
28
LockingPolicy class are to provide Lock and Unlock methods.
30
template < typename SharedObject, typename LockingPolicy = LOKI_DEFAULT_MUTEX,
31
template<class> class ConstPolicy = LOKI_DEFAULT_CONSTNESS >
36
typedef typename ConstPolicy<SharedObject>::Type ConstOrNotType;
38
/** Constructor locks mutex associated with an object.
39
@param object Reference to object.
40
@param mutex Mutex used to control thread access to object.
42
LockingPtr( volatile ConstOrNotType & object, LockingPolicy & mutex )
43
: pObject_( const_cast< SharedObject * >( &object ) ),
49
typedef typename std::pair<volatile ConstOrNotType *, LockingPolicy *> Pair;
51
/** Constructor locks mutex associated with an object.
52
@param lockpair a std::pair of pointers to the object and the mutex
54
LockingPtr( Pair lockpair )
55
: pObject_( const_cast< SharedObject * >( lockpair.first ) ),
56
pMutex_( lockpair.second )
58
lockpair.second->Lock();
61
/// Destructor unlocks the mutex.
67
/// Star-operator dereferences pointer.
68
ConstOrNotType & operator * ()
73
/// Point-operator returns pointer to object.
74
ConstOrNotType * operator -> ()
81
/// Default constructor is not implemented.
84
/// Copy-constructor is not implemented.
85
LockingPtr( const LockingPtr & );
87
/// Copy-assignment-operator is not implemented.
88
LockingPtr & operator = ( const LockingPtr & );
90
/// Pointer to the shared object.
91
ConstOrNotType * pObject_;
93
/// Pointer to the mutex.
94
LockingPolicy * pMutex_;
96
}; // end class LockingPtr
100
#endif // end file guardian