Re: Questionable advice
On Friday, September 20, 2013 2:59:32 PM UTC+2, James Kanze wrote:
On Friday, 20 September 2013 12:18:26 UTC+1, SG wrote:
On Wednesday, September 18, 2013 4:05:21 PM UTC+2, =D6=F6 Tiib wrote:
On Tuesday, 17 September 2013 14:43:54 UTC+3, Juha Nieminen wrote:
Also, there currently exists no ready-made solution for copy-on-wri=
te,
which is sometimes the most efficient solution to some problems.
Yes. Who wants to have lockless copy-on-write has to write it. Pointe=
r
to atomic refcount feels simplest candidate. If to propose one to boo=
st
then it probably eventually lands in C++.
std::shared_ptr makes implementing COW fairly easy. Just saying.
Thread-safe? (std::shared_ptr is thread safe, but I have my
doubts about a COW class which uses it.)
Yes. As long as all concurrent const-accesses to the pointee are
thread-safe, the COW wrapper will be as thread-safe. Read/write
accessors might look like this:
T const& read() const
{
return *(this->sptr);
}
T& write()
{
if (!this->sptr.unique())
this->sptr = make_shared<T>(read());
assert(this->sptr.unique());
return *(this->sptr);
}
and you're done. This will be thread-safe in the useful definition
kind of way of thread-safety. By that I mean that two threads working
on the same _wrapper_ object still requires synchronization. So, in
case there is no concurrent access to such a wrapper, everything is
fine. In particular, the uniqueness won't suddenly be gone between
the test and the return in the write function. For that to happen we
would need an unsynchronized concurrent access to that wrapper.
Threads accessing _different_ wrapper objects that share the same
pointee is perfectly fine. The worst thing that could happen here is
one unnecessary copy in case many threads want write access at the
exact same time because every thread would create a copy and the
original value would be discarded by every thread.
So, one does not need to fiddle around with atomics or mutexes to get
copy-on-write right. std::shared_ptr does that for you.
Cheers!
SG