Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2003-12-15 12:45:30


On Dec 15, 2003, at 8:45 AM, Michael Glassford wrote:

> What I'm really interested in doing, however, is getting the rw_mutex
> and
> related classes that are in the thread_dev branch into releasable
> shape and
> then getting them into a release; I think I can do this because I use
> them
> and have invested a lot of time in understanding, cleaning up, and
> somewhat
> improving them (though my changes are not in CVS and haven't even been
> posted yet).

Fwiw, I took a look at the rw_mutex about five months ago and posted
this:

http://article.gmane.org/gmane.comp.lib.boost.devel/22094/
match=+lock++thread+version

And after a little further reflection posted:

http://article.gmane.org/gmane.comp.lib.boost.devel/22140/
match=+lock++thread+version

I've since settled on the name lock_both instead of lock2 as proposed
in my second post.

Here is a complete example use of rw_mutex and lock_both:

class A
{
public:
     explicit A(int data) : data_(new int(data)) {}
     A(const A& a);
     A& operator=(const A& a);
 
     void write();
     int read() const;
 
private:
     std::tr1::shared_ptr<int> data_;
     mutable Metrowerks::rw_mutex mut_;
 
     typedef Metrowerks::rw_mutex::read_lock read_lock;
     typedef Metrowerks::rw_mutex::write_lock write_lock;
};
 
A::A(const A& a)
{
     read_lock lock(a.mut_);
     data_ = a.data_;
}
 
void
A::write()
{
     write_lock lock(mut_);
     ++*data_;
}
 
int
A::read() const
{
     read_lock lock(mut_);
     return *data_;
}

A&
A::operator=(const A& a)
{
     typedef Metrowerks::lock_both<read_lock, write_lock> lock_both;
     if (this != &a)
     {
         read_lock r(a.mut_, false);
         write_lock w(mut_, false);
         lock_both lock(r, w); // safe!
         data_ = a.data_;
     }
     return *this;
}

In this example the read_lock and write_lock are constructed with false
so as to not cause the constructor to lock the mutexes. And then
lock_both is used to atomically lock both the read_lock and the
write_lock.

I can contribute interface suggestions, but not implementation.

-Howard


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk