1 //vim: expandtab:shiftwidth=4:fileencoding=utf-8 :
3 /* Copyright ® 2009 Fulvio Satta
5 If you want contact me, send an email to Yota_VGA@users.sf.net
7 This file is part of Biscotto
9 Biscotto is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 Biscotto is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25 #include <boost/lambda/lambda.hpp>
29 void Cache::Monitor::operator()()
31 FAST_LOCK_O(cache().mutex
);
35 /* Iterate if the cache must delete some element */
36 for (typeof(cache().order
.begin()) i
= cache().order
.begin();
37 i
!= cache().order
.end() and (cache().size
>= cache().max
or
41 /* Delete some object */
42 CacheObject
*object
= i
->second
;
43 if (not object
->destroy())
48 cache().delfirst
= false;
51 /* Rescan the first index */
52 cache().first
= cache().order
.begin()->first
;
54 /* Notify that the first is deleted */
56 cache().waitdelfirst
.notify_all();
58 /* Wait for the next cache optimization */
60 cache().command
.wait(guard
);
64 Cache::Cache() : position(0), first(0), delfirst(false), max(1024 * 1024 * 10)
66 /* Launch the thread monitor */
67 boost::thread(Monitor());
70 void Cache::add(CacheObject
&object
)
74 /* Wait if the first must be deleted */
75 waitdelfirst
.wait(guard
, boost::lambda::var(delfirst
));
77 /* Add the new object */
78 object
.setPosition(position
);
79 order
[position
++] = &object
;
80 objects
.insert(&object
);
83 size
+= object
.size();
85 /* If the first must be deleted */
86 if (position
== first
)
89 /* If the cache should be optimized */
90 if (size
>= max
or delfirst
)
97 void Cache::del(CacheObject
&object
)
99 size
-= object
.size();
100 order
.erase(object
.position());
101 objects
.erase(&object
);
104 void Cache::resize(long int delta
)
110 /* If the size should be optimized */
114 command
.notify_one();
118 void Cache::use(CacheObject
&object
)
122 /* Wait if the first must be deleted */
123 waitdelfirst
.wait(guard
, boost::lambda::var(delfirst
));
125 order
.erase(object
.position());
126 object
.setPosition(position
++);
127 order
[position
] = &object
;
130 void Cache::setLimit(unsigned long int limit
)
137 unsigned long int Cache::limit() const
144 CacheObject
*Cache::readPointer(CacheObject
**ptr
) const
148 (*ptr
)->incprotect();