locked_object.h

Go to the documentation of this file.
00001 #ifndef LOCKED_OBJECT_CLASS
00002 #define LOCKED_OBJECT_CLASS
00003 
00004 /*****************************************************************************\
00005 *                                                                             *
00006 *  Name   : locked_object                                                     *
00007 *  Author : Chris Koeritz                                                     *
00008 *                                                                             *
00009 *******************************************************************************
00010 * Copyright (c) 2002-$now By Author.  This program is free software; you can  *
00011 * redistribute it and/or modify it under the terms of the GNU General Public  *
00012 * License as published by the Free Software Foundation; either version 2 of   *
00013 * the License or (at your option) any later version.  This is online at:      *
00014 *     http://www.fsf.org/copyleft/gpl.html                                    *
00015 * Please send any updates to: fred@gruntose.com                               *
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   // not permitted.
00094   locked_object(const locked_object &);
00095   locked_object &operator =(const locked_object &);
00096 };
00097 
00098 #endif
00099 

Generated on Fri Nov 28 04:29:08 2008 for HOOPLE Libraries by  doxygen 1.5.1