- Main Page
- Namespaces
- Classes
- Files
- Related Pages

# /Users/fpy/titan-1-5-MBARI/Mers/Utils/Lang/ReferencedObject.cpp

    00001
    00002 //
    00003 // Copyright (c) 2004           Model-based Embedded and Robotic Systems Group
    00004 // All Rights Reserved          Massachusetts Institute of Technology
    00005 //
    00006 // This software is provided as is. Model-based Embedded and Robotic Systems
    00007 // (MERS) group does not assume any responsibility.
    00008 //
    00009 // Organization:        Model-based Embedded and Robotic Systems Group
    00010 //                                      Massachusetts Institute of Technology
    00011 //
    00013
    00014 #include "ReferencedObject.h"
    00015
    00016 using Mers::Utils::Lang::ReferencedObject;
    00017
    00019
    00020 ReferencedObject::ReferencedObject() : mNumberOfReferences(0)
    00021 {
    00022         //int error =
    00023                 pthread_mutex_init(&mReferencedObjectMutex, NULL);
    00024         //if(error){
    00025         //      printf("Unable to initialize referenced object mutex\n");
    00026         //}
    00027 }
    00028
    00030
    00031 ReferencedObject::~ReferencedObject()
    00032 {
    00033         // Cleanup our mutex now that we don't need it anymore.
    00034         pthread_mutex_destroy( &mReferencedObjectMutex );
    00035 }
    00036
    00038
    00039 void ReferencedObject::addReference()
    00040 {
    00041         lockReferencedObject();
    00042         // Add another reference.
    00043         ++mNumberOfReferences;
    00044         unlockReferencedObject();
    00045 }
    00046
    00048
    00049 void ReferencedObject::removeReference()
    00050 {
    00051         bool cleanupObject = false;
    00052
    00053         lockReferencedObject();
    00054         // Sanity check - if we already have 0 references, just delete ourself.
    00055         if (mNumberOfReferences > 0) {
    00056                 --mNumberOfReferences;
    00057         }
    00058         cleanupObject = (mNumberOfReferences == 0);
    00059         // Note that we must unlock our object before we can delete it -
    00060         // need to make sure that we don't access any functions within this
    00061         // after deleting it.
    00062         unlockReferencedObject();
    00063
    00064         if(cleanupObject)
    00065                 delete this;
    00066 }
    00067
    00069
    00070 void ReferencedObject::lockReferencedObject()
    00071 {
    00072         pthread_mutex_lock(&mReferencedObjectMutex);
    00073 }
    00074
    00076
    00077 void ReferencedObject::unlockReferencedObject()
    00078 {
    00079         pthread_mutex_unlock(&mReferencedObjectMutex);
    00080 }
    00081
    00083