Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2003-07-14 14:58:23


On Sunday, July 13, 2003, at 07:04 PM, Howard Hinnant wrote:

> class rw_mutex
> {
> public:
> typedef detail::read_lock<rw_mutex> read_lock;
> typedef detail::write_lock<rw_mutex> write_lock;
> ...
> };
>
> I'm not picky about the names read_lock and write_lock. Then these
> locks could have the "standard" scoped_lock interface. So the "A"
> example above would look more like:
>
> class A
> {
> public:
> ...
> void read() const
> {
> boost::rw_mutex::read_lock lock(mut_);
> ...
> }
>
> void write()
> {
> boost::rw_mutex::write_lock lock(mut_);
> ...
> }
> ...
> private:
> ...
> mutable boost::rw_mutex mut_;
> };

I've been thinking about this a little more...

A (try_)scoped_lock of multiple (say 2) try_scoped_lock's would be very
handy. Something like:

template <class TryLock1, class TryLock2>
class lock2
{
public:
     lock2(TryLock1& m1, TryLock2& m2, bool lock_it = true);

     ~lock2();

     void lock();
     bool try_lock();
     void unlock();
     bool locked() const;
     operator int bool_type::* () const;

private:
     lock2(const lock2&);
     lock2& operator=(const lock2&);
};

(I'm not happy with the name lock2)

TryLock1&2 are models of scoped_try_lock, not try_mutex. lock2 will
"atomically" lock m1 and m2 without deadlocking (perhaps using the try
and back off algorithm).

Given lock2, and if the read/write_lock's model a try_lock, then the
example "A" above can be expanded to include A's operator=:

A&
A::operator=(const A& a)
{
     typedef rw_mutex::write_lock write_lock;
     typedef rw_mutex::read_lock read_lock;
     typedef lock2<write_lock, read_lock> rw_lock;

     if (this != &a)
     {
         write_lock w(mut_, false);
         read_lock r(a.mut_, false);
         rw_lock lock(w, r);
         // Now you can safely do assign ...
     }
     return *this;
}

Comments?

-Howard


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