The boost::lock_guard
structure implements the RAII idiom (Resource Allocation is Intialization), and thus automatically locks upon construction and unlocks on destruction. When this happens depends on the usual C++ rules, i.e. when the structure leaves the scope that the boost::lock_guard
was created in.
For instance:
void TestFunction( void ) {
// Do non-blocking operations:
{
// Lock the Mutex:
boost::lock_guard<boost::mutex> lockGuard( mutex_lock_symbol );
// Do blocking operations
} // Exit scope the boost::lock_guard was created in and therefore destroy it (thus unlock the mutex)
// Do more non-blocking operations:
}
This just helps you control the number of operations for which the mutex is locked for by creating a new scope in which the boost::lock_guard
is created. The other advantage of boost::lock_guard
is that it is exception safe.
In the two examples you have given, because there is no other code outside of the scope in the first example the functionality of the two examples is the same.