1

我目前使用boost lockguard如下但是我对花括号的使用仍然有点困惑。我想知道这两个是否相同

void ThreadSafeMethod()
{
   {//Begin Lock
      boost::lock_guard<boost::mutex> lock(mutex_lock_symbol);
      ....
      ....
   }//End Lock
}

或者这种消除一层花括号的方法。这是否正确且与上述相同?

void ThreadSafeMethod()
{//Locks automatically 
      boost::lock_guard<boost::mutex> lock(mutex_lock_symbol);
}//Unlocks
4

2 回答 2

2

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.

于 2013-06-13T17:16:56.310 回答
1

是的,它们是相同的,只要您在内大括号后不添加任何代码。

基本上,花括号限制了 lock_guard 存在的范围,从而限制了它的解锁时间。没有内大括号,函数退出时会解锁;与他们一起,当它离开内部块时。但是,由于在您的示例中,离开块和离开函数之间没有发生任何事情,因此它们是同一回事。

于 2013-06-13T17:09:07.090 回答