简体   繁体   English

boost scoped_lock vs普通锁定/解锁

[英]boost scoped_lock vs plain lock/unlock

I'm going to use boost::mutex from boost/thread/mutex.hpp . 我将使用boost/thread/mutex.hpp boost::mutex There are several ways to lock/unlock mutex: with scoped_lock , unique_lock , lock_guard , mutex's member functions ::lock() and ::unlock() and nonmember functions lock() and unlock() . 有几种方法可以锁定/解锁互斥锁:使用scoped_lockunique_locklock_guard ,互斥锁的成员函数::lock()::unlock()以及非成员函数lock()unlock()

I noticed, that boost::scoped_mutex is one of the most popular ways of using mutex. 我注意到, boost::scoped_mutex是最流行的使用互斥锁的方法之一。 Why is it preferable to member functions ::lock() and ::unlock() ? 为什么它更适合成员函数::lock()::unlock()

Particularly, why should I use 特别是,我为什么要使用

{
  boost::scoped_lock lock(mutex)
  // ...
  // read/output sharing memory.
  // ...
}

rather than 而不是

mutex.lock()
// ...
// read/output sharing memory.
// ...
mutex.unlock()

is scoped_lock better just because of some style-coding point of view or is ::lock()/::unlock() not "thread safe enough"? scoped_lock更好只是因为一些样式编码的观点或是::lock()/::unlock()不是“线程足够安全”?

Why is it preferable to member functions ::lock() and ::unlock()? 为什么它更适合成员函数:: lock()和:: unlock()?

For the same reason why the RAII idiom became popular in general (this is just one of its countless instances): because you can be sure you don' leave the current scope without unlocking the mutex. 出于同样的原因,为什么RAII成语在一般情况下变得流行(这只是其无数例中的一个):因为你可以确定你不会在不解锁互斥锁的情况下离开当前范围。

Notice, that this is not just about forgetting to call unlock() : an exception may occur while your mutex is locked, and your call to unlock() may never be reached, even though you do not have any return statement between your call to lock() and your call to unlock() . 请注意,这不仅仅是忘记调用unlock() :当你的互斥锁被锁定时可能会发生异常,并且可能永远不会达到你对unlock()调用,即使你的调用之间没有任何return语句。 lock()和你对unlock()调用。

m.lock() // m is a mutex
// ...
foo(); // If this throws, your mutex won't get unlocked
// ...
m.unlock()

In this case, the destructor of your scoped_lock guard will be invoked during stack unwinding, making sure the associated mutex always gets released. 在这种情况下,将在堆栈展开期间调用scoped_lock防护的析构函数,确保关联的互斥锁始终被释放。

{
    boost::scoped_lock lock(m); // m is a mutex
    // ...
    foo(); // If this throws, your RAII wrapper will unlock the mutex
    // ...
}

Moreover, in many situations this will improve your code's readability, in that you won't have to add a call to unlock() before every return statement. 此外,在许多情况下,这将提高代码的可读性,因为您不必在每个return语句之前添加对unlock()的调用。

you can use 您可以使用

std::lock_guard<std::mutex> lock(mutex);

if don't want to use boost library. 如果不想使用boost库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM