Monday, January 12, 2009

Boost scoped lock

I have been very impressed with the Boost libraries. Each day I'm finding more and more uses of Boost that make C++ programming easier.

My latest enjoyment comes from boost::mutex::scoped_lock.

scoped_lock follows the RAII (Resource Allocation Is Initialization) pattern. When the lock is constructed it holds onto the mutex until it is destructed.

Here is a simple example:

class Foo
void bar()
// Will grab the resource or wait until free
::boost::mutex::scoped_lock lock(m_mutex);
//Critical section

// No need to unlock the lock will do that itself.
boost::mutex m_mutex;

One word of caution. Up to Boost 1.36 the behavior of the mutex was different on Windows vs Linux. On Windows the lock would be recursive, that is you could call another method and enter it your thread already held that lock. Whereas on Linux that would cause a deadlock. The 1.37 version has fixed this issue and the both behave like the Linux version.


Anonymous said...

unlock will be called just after lock, because the scope of temporarily variable is finished in the same point it was created. To correct work it should be "boost::mutex::scoped_lock lock(m_mutex);"

developer-resource said...

Your right