|
Boost : |
From: Eric Niebler (eric_at_[hidden])
Date: 2004-07-19 13:05:18
Rob Stewart wrote:
> From: "Peter Dimov" <pdimov_at_[hidden]>
>
>>Also, I still think that the bool parameter is better than a "locking" enum,
>>as evidenced by the use case shown in the specification:
>>
>> scoped_lock lock( m, want_to_lock? locking: non_locking );
>>
>>I find this an unnecessarily verbose and contrived way to express
>>
>> scoped_lock lock( m, want_to_lock );
>>
>>which is the original intent.
>
>
> I disagree. From the perspective of calling code, using a bool
> makes things more confusing:
>
> scoped_lock lock1(m, true);
> scoped_lock lock2(m, false);
>
>>From this context, it isn't apparent what "true" and "false"
> mean. Yes, you can refer to the documentation, but what if
> you're new to scoped_lock and you forget what it means? Then
> you'll have to switch contexts, find the docuementation, read
> about the parameter, and then switch back to see what's really
> happening in the code.
>
> With the enum, however, the code is self-documenting:
>
> scoped_lock lock1(m, locking);
> scoped_lock lock2(m, non_locking);
>
> Thus, using the enum eliminates a source of errors and confusion
> whereas the conditional behavior you mention is still possible,
> if verbose.
>
With a movable lock, you could do this:
scoped_lock lock_if( Mutex & m, bool lock_it )
{
return scoped_lock( m, lock_it ? locking : non_locking );
}
And now the point of use looks like:
scoped_lock l = lock_if( m, my_condition );
As I've mentioned previously, I prefer to drop the enum entirely and use
a helper function to defer taking the lock:
scope_lock l = defer_lock( m );
Given such a scheme, lock_if as defined above would be implemented as:
scoped_lock lock_if( Mutex & m, bool lock_it )
{
scoped_lock l = defer_lock( m );
if( lock_it )
l.lock();
return m;
}
Movable locks open up all sorts of interesting interface possibilities.
-- Eric Niebler Boost Consulting www.boost-consulting.com
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk