LockingPtr.h

00001 
00002 // The Loki Library
00003 // Copyright (c) 2001 by Andrei Alexandrescu
00004 // This code is from the article:
00005 //     "Generic<Programming>: volatile ó Multithreaded Programmerís Best Friend
00006 //     Volatile-Correctness or How to Have Your Compiler Detect Race Conditions
00007 //     for You" by Alexandrescu, Andrei.
00008 //     Published in the February 2001 issue of the C/C++ Users Journal.
00009 //     http://www.cuj.com/documents/s=7998/cujcexp1902alexandr/
00010 // Prepared for Loki library by Richard Sposato
00012 #ifndef LOKI_LOCKING_PTR_INC_
00013 #define LOKI_LOCKING_PTR_INC_
00014 
00015 // $Id: LockingPtr.h 748 2006-10-17 19:49:08Z syntheticpp $
00016 
00017 
00018 #include <loki/ConstPolicy.h>
00019 
00020 namespace Loki
00021 {
00030     template < typename SharedObject, typename LockingPolicy = LOKI_DEFAULT_MUTEX, 
00031                template<class> class ConstPolicy = LOKI_DEFAULT_CONSTNESS >
00032     class LockingPtr
00033     {
00034     public:
00035 
00036         typedef typename ConstPolicy<SharedObject>::Type ConstOrNotType;
00037 
00042         LockingPtr( volatile ConstOrNotType & object, LockingPolicy & mutex )
00043            : pObject_( const_cast< SharedObject * >( &object ) ),
00044             pMutex_( &mutex )
00045         {
00046             mutex.Lock();
00047         }
00048 
00049         typedef typename std::pair<volatile ConstOrNotType *, LockingPolicy *> Pair;
00050 
00054         LockingPtr( Pair lockpair )
00055            : pObject_( const_cast< SharedObject * >( lockpair.first ) ),
00056             pMutex_( lockpair.second )
00057         {
00058             lockpair.second->Lock();
00059         }
00060 
00062         ~LockingPtr()
00063         {
00064             pMutex_->Unlock();
00065         }
00066 
00068         ConstOrNotType & operator * ()
00069         {
00070             return *pObject_;
00071         }
00072 
00074         ConstOrNotType * operator -> ()
00075         {
00076             return pObject_;
00077         }
00078 
00079     private:
00080 
00082         LockingPtr();
00083 
00085         LockingPtr( const LockingPtr & );
00086 
00088         LockingPtr & operator = ( const LockingPtr & );
00089 
00091         ConstOrNotType * pObject_;
00092 
00094         LockingPolicy * pMutex_;
00095 
00096     }; // end class LockingPtr
00097 
00098 } // namespace Loki
00099 
00100 #endif // end file guardian
00101 

Generated on Sun Feb 25 16:52:26 2007 for Loki by  doxygen 1.5.1-p1