Boost logo

Boost :

From: Eric Niebler (eric_at_[hidden])
Date: 2004-07-22 12:16:49

Howard Hinnant wrote:
> On Jul 22, 2004, at 9:41 AM, Michael Glassford wrote:
>> What can you do to a mutex except lock it with a lock object?
> My comments were based on the fact that currently the mutex interface is
> private except for construction and destruction. This is meant to
> encourage the programmer to use the mutex only in an orderly (RAII)
> fashion.
> <soapbox>
> However we do not currently prohibit code such as the following:
> typedef mutex::scoped_lock MyMutex;
> mutex m;
> MyMutex my_mut(m, false);
> void foo()
> {
> my_mut.lock();
> }
> void bar()
> {
> my_mut.unlock();
> }
> int main()
> {
> foo();
> bar();
> }
> I.e. It is not difficult to make a lock look exactly like a mutex with
> public member functions, and then use it in whatever way (orderly or
> not) you want to. Given that, perhaps it is better to just make the
> mutex interface public in the first place, and expose the mutex of a
> lock.

Please no. The scoped_lock keeps track of whether it has locked the
mutext or not, so it kows whether or not to unlock the mutex in its
destructor. If you make the mutex interface public AND expose the mutex
of the lock, you break encapsulation:

mutext m;

   scoped_lock l( m ); // locked
   l.mutext()->unlock(); // unlocked
} // unlocked again by l's destructor!

It is for precisely this reason that I think you shouldn't be able to
get a pointer to the mutex from the scoped_lock. You should get back a
token or a void* that is useful only for comparison purposes.

Eric Niebler
Boost Consulting

Boost list run by bdawes at, gregod at, cpdaniel at, john at