00001 #ifndef GARBAGE_H 00002 #define GARBAGE_H 00003 00004 00005 #include "arraylist.h" 00006 #include "garbage.inc" 00007 #include "mutex.inc" 00008 00009 // Garbage collection 00010 // The objects inherit from GarbageObject. 00011 // The constructor sets users to 0 so the caller must call add_user if it 00012 // wants to use it. If it doesn't intend to use it after calling the constructor, 00013 // it should not call add_user. 00014 // Other users of the object must call add_user to increment the user count 00015 // and remove_user to decriment the user count. 00016 // The object is only deleted if a call to Garbage::delete_object is made and 00017 // the user count is 0. 00018 // A user who is using it and wants to delete it must first call 00019 // remove_user and then call Garbage::delete_object. 00020 00021 00022 // They are deleted by calling delete_object. They get deleted at a 00023 // random point later on. The objects must not change anything in their 00024 // destructors. 00025 00026 // Can't make graphics elements inherit because they must be deleted 00027 // when the window is locked and they change their parent pointers. 00028 00029 // Elements of link lists must first be unlinked with remove_pointer and then 00030 // passed to delete_object. 00031 00032 // ArrayList objects must be deleted one at a time with delete_object. 00033 // Then the pointers must be deleted with remove_all. 00034 class GarbageObject 00035 { 00036 public: 00037 GarbageObject(char *title); 00038 virtual ~GarbageObject(); 00039 00040 // Called when user begins to use the object. 00041 void add_user(); 00042 // Called when user is done with the object. 00043 void remove_user(); 00044 00045 int users; 00046 int deleted; 00047 char *title; 00048 }; 00049 00050 00051 00052 class Garbage 00053 { 00054 public: 00055 Garbage(); 00056 ~Garbage(); 00057 00058 // Called by GarbageObject constructor 00059 void add_object(GarbageObject *ptr); 00060 00061 // Called by user to delete the object. 00062 // Flags the object for deletion as soon as it has no users. 00063 static void delete_object(GarbageObject *ptr); 00064 00065 00066 // Called by remove_user and delete_object 00067 static void remove_expired(); 00068 Mutex *lock; 00069 ArrayList<GarbageObject*> objects; 00070 00071 // Global garbage collector 00072 static Garbage *garbage; 00073 }; 00074 00075 00076 00077 #endif
1.5.5