00001 // $Id: flexlock.h,v 1.8 2008/12/21 09:40:47 dvermeir Exp $ 00002 #ifndef DV_THREAD_FLEXLOCK_H 00003 #define DV_THREAD_FLEXLOCK_H 00004 00005 #include <string> 00006 #include <iostream> 00007 #include <dvutil/debug.h> 00008 #include <dvthread/monitor.h> 00009 #include <dvthread/thread.h> 00010 00011 namespace Dv { 00012 namespace Thread { 00013 00014 /** Convenience class to synchronize access to a Monitor object. 00015 * The difference with Dv::Thread::Lock is that if the 00016 * constructing thread already owns the monitor, it 00017 * does no attempt to enter it (and does not attempt 00018 * to exit it upon destruction). 00019 * 00020 * Example usage: 00021 * @code 00022 * class SomeClassToProtect: public Dv::Thread::Monitor { 00023 * public: 00024 * voif f() { 00025 * FlexLock lock(*this, "f", &cerr); // enter monitor 00026 * g() 00027 * // destructor of lock will exit the monitor. 00028 * } 00029 * 00030 * void g() { 00031 * FlexLock lock(*this, "g", &cerr); // enter monitor, but not if called from f 00032 * .. 00033 * } 00034 * ... 00035 * }; 00036 * @endcode 00037 * @sa Dv::Thread::Lock 00038 */ 00039 class FlexLock: public DebugSlave { 00040 public: 00041 /** Constructor. This function will enter the monitor parameter unless 00042 * the current thread is already the owner of the monitor. 00043 * Writing to FlexLock::log() will write to its monitor's log. 00044 * @param m monitor to enter. 00045 * @param msg optional message to print to log 00046 * @see Monitor::enter 00047 */ 00048 FlexLock(Monitor& m, const std::string& msg=""); 00049 /** 00050 * Destructor. This function will exit the monitor. 00051 * @exception runtime_error if the current thread is not 00052 * in the monitor (e.g. if m.exit() was called before the 00053 * destructor of the Lock). 00054 * @see Monitor::exit() 00055 */ 00056 ~FlexLock(); 00057 /** @return true iff the constructor actually entered the monitor. */ 00058 bool entered() const { return entered_; } 00059 private: 00060 Debugable* debug_master() const { return &monitor_; } 00061 00062 /** Monitor on which FlexLock is defined. */ 00063 Monitor& monitor_; 00064 /** Message to print on construction and destruction. */ 00065 const std::string msg_; 00066 /** If non-zero, pointer to stream on which to log info. */ 00067 Dv::ostream_ptr log_; 00068 /** Was the monitor actually entered upon construction. */ 00069 bool entered_; 00070 }; 00071 } 00072 } 00073 00074 #endif
dvthread-0.13.4 | [11 December, 2009] |