00001 // $Id: lock.h,v 1.6 2006/06/20 17:50:45 dvermeir Exp $ 00002 #ifndef DV_THREAD_LOCK_H 00003 #define DV_THREAD_LOCK_H 00004 00005 #include <string> 00006 #include <iostream> 00007 #include <dvthread/monitor.h> 00008 #include <dvthread/thread.h> 00009 00010 namespace Dv { 00011 namespace Thread { 00012 00013 /** 00014 * Convenience class to synchronize access to a Monitor object. 00015 * Creating a lock enters the monitor, destroying the lock exits the 00016 * monitor. 00017 * 00018 * Example usage: 00019 * @code 00020 * class SomeClassToProtect: public Dv::Thread::Monitor { 00021 * public: 00022 * voif f() { 00023 * Lock lock(*this, "f", &cerr); // enter monitor 00024 * access the object 00025 * // destructor of lock will exit the monitor. 00026 * } 00027 * ... 00028 * }; 00029 * @endcode 00030 * 00031 * The lock declaration can be abbreviated using the Java-inspired 00032 * @ref Dv::Thread::SYNCHRONIZED "SYNCHRONIZED" macro. 00033 */ 00034 class Lock { 00035 public: 00036 /** 00037 * Constructor. This function will enter the monitor parameter. 00038 * 00039 * @param m monitor to enter. 00040 * @param msg optional message to print to log 00041 * @param log if nonzero, the message will be printed both 00042 * on creation and destruction of the lock. 00043 * @see Monitor::enter 00044 */ 00045 Lock(Monitor& m, const std::string& msg="", std::ostream* log=0); 00046 /** 00047 * Destructor. This function will exit the monitor. 00048 * @exception runtime_error if the current thread is not 00049 * in the monitor (e.g. if m.exit() was called before the 00050 * destructor of the Lock). 00051 * @see Monitor::exit() 00052 */ 00053 ~Lock() throw (std::runtime_error); 00054 private: 00055 /** Monitor on which lock is defined. */ 00056 Monitor& monitor_; 00057 /** Message to print on construction and destruction. */ 00058 const std::string msg_; 00059 /** If non-zero, pointer to stream on which to log info. */ 00060 std::ostream* log_; 00061 }; 00062 } 00063 } 00064 00065 /** 00066 * Convenience macro. Put this in the beginning of a member function 00067 * of a subclass of a Monitor object to ensure exclusive access to 00068 * some resource. Inspired by Java keyword. 00069 * @code 00070 * class Buffer: public Dv::Thread::Monitor { 00071 * public: 00072 * int get() { SYNCHRONIZED retrieve & remove item; } 00073 * void put(int) { SYNCHRONIZED add item; } 00074 * }; 00075 * @endcode 00076 */ 00077 #define SYNCHRONIZED Dv::Thread::Lock lock(*this); 00078 00079 #endif
dvthread-0.5.0 | [22 June, 2006] |