
Peter Dimov wrote:
Eric Niebler wrote:
I continue to believe that a better interface for a unified lock involves descriptively named helper functions:
scoped_lock l1( m ); // lock unconditionally scoped_lock l1 = defer_lock( m ); // don't lock scoped_lock l2 = try_lock( m ); // try lock scoped_lock l3 = timed_lock( m, t ); // timed lock
Maybe. Do you have a sketch of the specification? (Not the implementation.)
I don't, and I have family in town until Wednesday. (Arg! Lame answer, I know.) I just looked for my post in the ASPN archive, and it seems to have vanished into the ether, so I'm reproducing the code here. struct lock; lock try_lock(); struct lock_ref { lock_ref(lock & ref) : ref_(ref) { } lock & ref_; }; struct lock { lock(lock_ref ref) { // ... move the lock from ref.ref_ ... } operator lock_ref() { return lock_ref(*this); } operator bool() const { // TODO return true iff we're holding the lock return true; } private: friend lock try_lock(); lock(/*params*/){} // a try-lock c'tor // make this type non-copyable, non-assignable lock(lock &); lock & operator=(lock &); }; inline lock try_lock(/*params*/) { // call a special try-lock c'tor on lock return lock(/*params*/); } int main() { if( lock l = try_lock(/*params*/) ) {} } The idea is to have just one lock class (leaving aside read/write locks) and a collection of factory functions like try_lock(), timed_lock(), defered_lock() etc. Those functions create a lock object by calling the appropriate (private) constructor and returning the new lock object. (Some fancy auto_ptr-like move shenanigans are needed to make the lock return-able but not copy-able.) -- Eric Niebler Boost Consulting www.boost-consulting.com