C++ std::lock_guard详解
C语言题库
共 384字,需浏览 1分钟
·
2021-12-23 13:46
01
—
std::lock_guard详解
std::lock_guard属于C++11特性,锁管理遵循RAII习语管理资源,锁管理器在构造函数中自动绑定它的互斥体并加锁,在析构函数中解锁,大大减少了死锁的风险。下面我们来看一段代码。
#include
#include
#include
class Widget{
public:
Widget() = default;
~Widget() = default;
void fun(){
std::lock_guard<std::mutex> lock(lock_);
std::cout << "Widget::fun run" << std::endl;
}
private:
std::mutex lock_;
};
void TestThread1(Widget* w){
w->fun();
}
int main()
{
Widget* w = new Widget();
std::thread t1(&TestThread1, w);
t1.join();
return 0;
}
这是std::lock_gurad最基本的使用,程序在std::lock_guard生命周期内加锁和解锁,其中加锁和解锁分别在构造函数和析构函数中完成,具体如何我们看下std::lock_guard的构造函数和析构函数。
template <class _Mutex>
class _LIBCPP_TEMPLATE_VIS _LIBCPP_THREAD_SAFETY_ANNOTATION(scoped_lockable)
lock_guard
{
public:
typedef _Mutex mutex_type;
private:
mutex_type& __m_;
public:
_LIBCPP_NODISCARD_EXT _LIBCPP_INLINE_VISIBILITY
explicit lock_guard(mutex_type& __m) _LIBCPP_THREAD_SAFETY_ANNOTATION(acquire_capability(__m))
: __m_(__m) {__m_.lock();}
_LIBCPP_NODISCARD_EXT _LIBCPP_INLINE_VISIBILITY
lock_guard(mutex_type& __m, adopt_lock_t) _LIBCPP_THREAD_SAFETY_ANNOTATION(requires_capability(__m))
: __m_(__m) {}
_LIBCPP_INLINE_VISIBILITY
~lock_guard() _LIBCPP_THREAD_SAFETY_ANNOTATION(release_capability()) {__m_.unlock();}
private:
lock_guard(lock_guard const&) _LIBCPP_EQUAL_DELETE;
lock_guard& operator=(lock_guard const&) _LIBCPP_EQUAL_DELETE;
};
评论