lock_guard与unique_lock源码
时间: 2023-11-20 08:07:44 浏览: 79
lock_guard和unique_lock是C++11中的两种线程安全锁定方式,它们都是用来保护共享资源的,但它们的实现方式略有不同。
lock_guard源码:
```c++
template<typename _Mutex>
class lock_guard
{
public:
typedef _Mutex mutex_type;
//构造函数,锁定互斥量
explicit lock_guard(mutex_type& __m) : _M_device(__m)
{
_M_device.lock();
}
//析构函数,释放互斥量
~lock_guard()
{
_M_device.unlock();
}
//禁止拷贝构造函数和赋值操作符
lock_guard(const lock_guard&) = delete;
lock_guard& operator=(const lock_guard&) = delete;
private:
mutex_type& _M_device;
};
```
在lock_guard的构造函数中,它会锁定传入的互斥量。在lock_guard的析构函数中,它会释放互斥量。这样,在lock_guard对象的生命周期中,只要它存在,它所锁定的互斥量就不会被其他线程所访问。
unique_lock源码:
```c++
template<typename _Mutex>
class unique_lock
{
public:
typedef _Mutex mutex_type;
//构造函数
unique_lock() noexcept
: _M_device(0), _M_owns(false)
{ }
explicit unique_lock(mutex_type& __m) noexcept
: _M_device(std::addressof(__m)), _M_owns(true)
{
_M_device->lock();
}
unique_lock(mutex_type& __m, defer_lock_t) noexcept
: _M_device(std::addressof(__m)), _M_owns(false)
{ }
unique_lock(mutex_type& __m, adopt_lock_t) noexcept
: _M_device(std::addressof(__m)), _M_owns(true)
{ }
template<typename _Clock, typename _Duration>
unique_lock(mutex_type& __m, const chrono::time_point<_Clock, _Duration>& __t)
: _M_device(std::addressof(__m)), _M_owns(false)
{
const auto __now = _Clock::now();
if (__now < __t)
{
const auto __d = chrono::duration_cast<chrono::milliseconds>(__t - __now);
if (_M_device->try_lock_for(__d))
_M_owns = true;
}
}
template<typename _Rep, typename _Period>
unique_lock(mutex_type& __m, const chrono::duration<_Rep, _Period>& __d)
: _M_device(std::addressof(__m)), _M_owns(false)
{
if (_M_device->try_lock_for(__d))
_M_owns = true;
}
//析构函数
~unique_lock() noexcept
{
if (_M_owns)
_M_device->unlock();
}
//加锁
void lock()
{
if (!_M_owns)
{
_M_device->lock();
_M_owns = true;
}
}
//尝试加锁
bool try_lock()
{
if (!_M_owns && _M_device->try_lock())
{
_M_owns = true;
return true;
}
return false;
}
//解锁
void unlock()
{
if (_M_owns)
{
_M_device->unlock();
_M_owns = false;
}
}
//释放锁定的互斥量
mutex_type* release() noexcept
{
mutex_type* __t = _M_device;
_M_device = 0;
_M_owns = false;
return __t;
}
//获取锁定的互斥量
mutex_type* mutex() const noexcept
{
return _M_device;
}
//获取锁定状态
bool owns_lock() const noexcept
{
return _M_owns;
}
//禁止拷贝构造函数和赋值操作符
unique_lock(const unique_lock&) = delete;
unique_lock& operator=(const unique_lock&) = delete;
private:
mutex_type* _M_device;
bool _M_owns;
};
```
unique_lock相对于lock_guard有更多的构造函数,可以更灵活地操作互斥量。unique_lock的默认构造函数和defer_lock_t构造函数不会锁定互斥量,而adopt_lock_t构造函数会假设当前线程已经锁定互斥量,直接使用。unique_lock还提供了try_lock、unlock、release等成员函数,可以更方便地操作互斥量。
总之,lock_guard和unique_lock的实现方式不同,但它们都可以用来保护共享资源的线程安全。在实际使用中,需要根据需求灵活选择。
阅读全文