Boost logo

Boost :

From: Hamish Mackenzie (hamish_at_[hidden])
Date: 2003-02-06 09:01:56


On Wed, 2003-02-05 at 18:09, Trey Jackson wrote:
> template<class LockingStrategy>
> class mySuperLockedClass : public LockingStrategy
> {
> public:
> void read()
> {
> LockingStrategy::readlock();
> // do stuff
> }
> void write()
> {
> LockingStrategy::writelock();
> // do stuff
> }
> };
>

...

> struct
> MutexLockingStrategy
> {
> boost::mutex m_;
> void readlock()
> {
> boost::mutex::scoped_lock l(m_);
> }
> void writelock()
> {
> boost::mutex::scoped_lock l(m_);
> }
> };
>

These scoped locks will go out of scope before you "do stuff".

You can extend the scope using something like...

template<class LockingStrategy>
class mySuperLockedClass : public LockingStrategy
{
public:
  void read()
  {
    typename LockingStrategy::read_lock_type l( this );
    // do stuff
  }
  void write()
  {
    typename LockingStrategy::write_lock_type l( this );
    // do stuff
  }
};

struct
MutexLockingStrategy
{
  boost::mutex m_;
  class read_lock_type
  {
  public:
    readlock_type( MutexLockingStrategy * s ) : l_( s->m_ )
  private:
    boost::mutex::scoped_lock l_;
  }
  class write_lock_type
  {
  public:
    writelock_type( MutexLockingStrategy * s ) : l_( s->m_ )
  private:
    boost::mutex::scoped_lock l_;
  }
};

// etc.

-- 
Hamish Mackenzie <hamish_at_[hidden]>

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