Boost logo

Boost :

From: Branko Èibej (branko.cibej_at_[hidden])
Date: 2000-09-15 04:37:53


Levente Farkas wrote:
>
> hi,
> I find an example where lock and unlock can be useful.
> suppose we'd like to protect a with m, but we don't would like to protect f
> (suppose it's long) and have the following code (if we have lock/unlock on
> mutex).
> -----------
> {
> boost::lock lock(m);
> for (int i = a.get(); i < 10; a.next())
> {
> <some code>
> m.unlock()
> f();
> m.lock();
> <some code>
> }
> }

I think this is a real problem, but you don't need to expose
lock() and unlock() to solve it. Instead you have a lock-inverter
class (which must be a friend of lock, yes, but I think that's
justified in this case):

  namespace boost {
    class invert_lock
    {
     public:
      invert_lock (lock& l)
        : lock_ref(l)
      {
        l.unlock();
      }

      ~invert_lock()
      {
        l.lock();
      }
     private:
      lock& lock_ref;
    };
  }

Your example becomes:

  {
    boost::lock lock(m);
    for (int i = a.get(); i < 10; a.next())
    {
      <some code>
      {
        boost::invert_lock unlock(lock);
        f();
      }
      <some code>
    }
  }

    Brane

-- 
Branko Èibej                 <branko.cibej_at_[hidden]>
HERMES SoftLab, Litijska 51, 1000 Ljubljana, Slovenia
voice: (+386 1) 586 53 49     fax: (+386 1) 586 52 70

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