00001 #ifndef LOCKED_OBJECT_CLASS
00002 #define LOCKED_OBJECT_CLASS
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00019
00029 #include <basis/function.h>
00030 #ifdef CATCH_ERRORS
00031 #include <basis/guards.h>
00032 #endif
00033 #include <basis/mutex.h>
00034
00035 template <class contents>
00036 class locked_object
00037 {
00038 public:
00039 locked_object(contents *object_held = NIL) { _the_object = object_held; }
00041
00046
00047
00049 ~locked_object() {
00050 contents *to_zap = swap(NIL);
00051 WHACK(to_zap);
00052 }
00053
00054 contents *lock_object() { _locking.lock(); return _the_object; }
00056
00061 void unlock_object(contents *to_unlock) {
00063
00065 if (to_unlock != _the_object) {
00066 #ifdef CATCH_ERRORS
00067 continuable_error("locked_object", "unlock_object",
00068 "erroneous pointer has been passed in");
00069 #endif
00070 #ifdef ERRORS_ARE_FATAL
00071 deadly_error("locked_object", "unlock_object",
00072 "erroneous pointer has been passed in");
00073 #endif
00074 }
00075 if (to_unlock != _the_object) return;
00076 _locking.unlock();
00077 }
00078
00079 contents *swap(contents *new_object) {
00081
00082 _locking.lock();
00083 contents *to_return = _the_object;
00084 _the_object = new_object;
00085 _locking.unlock();
00086 return to_return;
00087 }
00088
00089 private:
00090 contents *_the_object;
00091 mutex _locking;
00092
00093
00094 locked_object(const locked_object &);
00095 locked_object &operator =(const locked_object &);
00096 };
00097
00098 #endif
00099