MIGRATED to http://cwiki.apache.org/confluence/display/qpid/ScopedLocking

Always use scoped lockers to lock mutexes and the like. Don't do this:

 do_stuff(); // DANGER: lock never released if exception thrown here.

Instead use a "scoped locker". This is simply a class that does the "acquire" in its constructor and the "release" in its destructor:

  Locker locker(lock);

Not only does this save a bit of typing, it guarantees that the lock will be released even if an exception is thrown, because C++ guarantees to call destructors of all local variables on exit from a scope. This also protects you forgetting to release the lock at every exit point from a function with multiple exit points - the compiler takes care of it for you. This technique applies more generally to any situation where you have to acquire and release resources. std::auto_ptr is a similar tool for memory management.

CppTips/ScopedLocking (last edited 2009-09-20 23:51:27 by localhost)