Simple copy-on-write framework
Hi!
I recently stumbled over the fact that using existing tools it is quite easy
to create a COW framework (almost) without any additional locking for
multithreaded code.
The idea is simple:
1. While you modify an object, you store it in a std::auto_ptr<T>. This
makes sharing the object impossible (due to auto_ptr's move semantics).
2. If you want to share an object, you store it in a boost::shared_ptr<T
const>.
Now, if you have an existing object, shared across threads via a
shared_ptr<T const> you obviously can't modify it, unless you first copy
it. For convenience, you store that copy in an auto_ptr<T> until you
finally assign that to the shared_ptr. This final assignment operation is
also the only place where you need a lock. Afterwards, your auto_ptr is
null and thus the only modifyable reference to the object is gone (unless
you cheated, of course) so if the object is thread-safe for concurrent
reads everything is fine.
In a related topic, the virtual copy construct comes in handy in this
context:
struct base {
virtual auto_ptr<base> clone() const = 0;
};
struct derived: base {
virtual auto_ptr<base> clone() const {
return auto_ptr<base>(new derived(*this));
}
};
A mutating operation then looks like this:
shared_ptr<T const> pc = get_ptr(); // uses locking
auto_ptr<T> p = pc->clone();
p->modify();
set_ptr(shared_ptr<T const>(p)); // uses locking
Quite simple and charming, so I thought I'd share it. And also of course to
get some peer review.
Uli
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]