问题描述
我要使用的boost ::互斥
从升压/线程/ mutex.hpp
。
有几种方法来锁定/解锁互斥:以的scoped_lock
, unique_lock
, lock_guard
,互斥的成员函数 ::锁()
和 ::解锁()
和非成员函数锁()
和解锁()
。
我注意到,那的boost :: scoped_mutex
是使用互斥的最流行的方式之一。为什么preferable成员函数 ::锁()
和 ::解锁()
?
特别是,我为什么要使用
{
提高:: scoped_lock的锁(互斥)
// ...
//读取/输出共享内存。
// ...
}
而不是
mutex.lock()
// ...
//读取/输出共享内存。
// ...
mutex.unlock()
是的scoped_lock
好只是因为从一些样式编码点或 ::锁()/解锁::()
不是线程足够安全?
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.
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()
.
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.
{
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.
这篇关于提高的scoped_lock VS纯锁定/解锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!