00001 // $Id: lock.h,v 1.12 2008/12/21 09:40:47 dvermeir Exp $ 00002 #ifndef DV_THREAD_LOCK_H 00003 #define DV_THREAD_LOCK_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 /** 00015 * Convenience class to synchronize access to a Monitor object. 00016 * Creating a lock enters the monitor, destroying the lock exits the 00017 * monitor. 00018 * 00019 * Example usage: 00020 * @code 00021 * class SomeClassToProtect: public Dv::Thread::Monitor { 00022 * public: 00023 * voif f() { 00024 * Lock lock(*this, "f", &cerr); // enter monitor 00025 * access the object 00026 * // destructor of lock will exit the monitor. 00027 * } 00028 * ... 00029 * }; 00030 * @endcode 00031 */ 00032 class Lock: DebugSlave { 00033 public: 00034 /** 00035 * Constructor. This function will enter the monitor parameter. 00036 * 00037 * @param m monitor to enter. 00038 * @param msg optional message to print to log 00039 * @see Monitor::enter 00040 */ 00041 Lock(Monitor& m, const std::string& msg=""); 00042 /** 00043 * Destructor. This function will exit the monitor. 00044 * @exception runtime_error if the current thread is not 00045 * in the monitor (e.g. if m.exit() was called before the 00046 * destructor of the Lock). 00047 * @see Monitor::exit() 00048 */ 00049 ~Lock(); 00050 00051 Debugable* debug_master() const { return &monitor_; } 00052 private: 00053 /** Monitor on which lock is defined. */ 00054 Monitor& monitor_; 00055 /** Message to print on construction and destruction. */ 00056 const std::string msg_; 00057 }; 00058 } 00059 } 00060 00061 #endif
dvthread-0.13.4 | [11 December, 2009] |