libzypp  10.5.0
MutexLock.h
Go to the documentation of this file.
00001 /*---------------------------------------------------------------------\
00002 |                          ____ _   __ __ ___                          |
00003 |                         |__  / \ / / . \ . \                         |
00004 |                           / / \ V /|  _/  _/                         |
00005 |                          / /__ | | | | | |                           |
00006 |                         /_____||_| |_| |_|                           |
00007 |                                                                      |
00008 \---------------------------------------------------------------------*/
00012 #ifndef   ZYPP_THREAD_MUTEXLOCK_H
00013 #define   ZYPP_THREAD_MUTEXLOCK_H
00014 
00015 #include <zypp/thread/Mutex.h>
00016 #include <cassert>
00017 
00018 
00020 namespace zypp
00021 { 
00022 
00023   namespace thread
00024   { 
00025 
00026 
00027     // -------------------------------------------------------------
00028     class MutexLock
00029     {
00030     public:
00031       explicit MutexLock(Mutex &mutex, bool init_locked=true)
00032         : m_mutex(&mutex)
00033         , m_locked(false)
00034       {
00035         if(init_locked)
00036           lock();
00037       }
00038 
00039       MutexLock(const MutexLock &ref)
00040         : m_mutex( ref.m_mutex)
00041         , m_locked(ref.m_locked)
00042       {
00043         ref.m_locked = false;
00044       }
00045 
00046       ~MutexLock()
00047       {
00048         try
00049         {
00050           if( m_locked)
00051             unlock();
00052         }
00053         catch( ... )
00054         {
00055           // don't let exceptions escape
00056         }
00057       }
00058 
00059       void lock()
00060       {
00061         assert(m_locked == false);
00062         m_mutex->lock();
00063         m_locked = true;
00064       }
00065 
00066       void unlock()
00067       {
00068         assert(m_locked == true);
00069         m_mutex->unlock();
00070         m_locked = false;
00071       }
00072 
00073       bool trylock()
00074       {
00075         assert(m_locked == false);
00076         m_locked = m_mutex->trylock();
00077         return m_locked;
00078       }
00079 
00080       bool locked()
00081       {
00082         return m_locked;
00083       }
00084 
00085     private:
00086       Mutex        *m_mutex;
00087       mutable bool  m_locked;
00088       //friend class Condition;
00089     };
00090 
00091 
00093   } // namespace thread
00096 } // namespace zypp
00098 
00099 #endif // ZYPP_THREAD_MUTEXLOCK_H
00100 /*
00101 ** vim: set ts=2 sts=2 sw=2 ai et:
00102 */