r858: Merge 2.1:
[cinelerra_cv.git] / cinelerra / garbage.C
blob57844dbb7b7cd9e31b7d69719b1d530f7ecfca84
1 #include "bcsignals.h"
2 #include "garbage.h"
3 #include "mutex.h"
5 #include <string.h>
7 Garbage *Garbage::garbage = 0;
10 GarbageObject::GarbageObject(char *title)
12         Garbage::garbage->add_object(this);
13         users = 0;
14         deleted = 0;
15         this->title = new char[strlen(title) + 1];
16         strcpy(this->title, title);
19 GarbageObject::~GarbageObject()
21         if(!deleted) 
22                 printf("GarbageObject::~GarbageObject: title=%s users=%d was not deleted by Garbage::delete_object\n", title, users);
23         delete [] title;
27 void GarbageObject::add_user()
29         Garbage::garbage->lock->lock("GarbageObject::add_user");
30         users++;
31         Garbage::garbage->lock->unlock();
34 void GarbageObject::remove_user()
36         Garbage::garbage->lock->lock("GarbageObject::add_user");
37         users--;
38         if(users < 0) printf("GarbageObject::remove_user: users=%d Should be >= 0.\n", users);
39         Garbage::garbage->remove_expired();
40 // *this is now invalid
41         Garbage::garbage->lock->unlock();
48 Garbage::Garbage()
50         lock = new Mutex("Garbage::lock", 1);
54 Garbage::~Garbage()
56         delete lock;
59 void Garbage::add_object(GarbageObject *ptr)
61         lock->lock("Garbage::add_object");
62         objects.append(ptr);
63         lock->unlock();
66 void Garbage::delete_object(GarbageObject *ptr)
68         Garbage *garbage = Garbage::garbage;
69         garbage->lock->lock("Garbage::delete_object");
70         ptr->deleted = 1;
72 // Remove expired objects here
73         remove_expired();
74         garbage->lock->unlock();
77 void Garbage::remove_expired()
79         Garbage *garbage = Garbage::garbage;
80         for(int i = 0; i < garbage->objects.total; i++)
81         {
82                 GarbageObject *ptr = garbage->objects.values[i];
83                 if(ptr->users <= 0 && ptr->deleted)
84                 {
85 // Must remove pointer to prevent recursive deletion of the same object.
86 // But i is still invalid.
87                         garbage->objects.remove_number(i);
89                         delete ptr;
90                         i--;
91                 }
92         }