std::unique_lock

280 阅读1分钟
explicit unique_lock(mutex_type& __m)
        : _M_device(std::__addressof(__m)), _M_owns(false) {
    lock();
    _M_owns = true;
}

unique_lock(mutex_type& __m, defer_lock_t) noexcept
: _M_device(std::__addressof(__m)), _M_owns(false) { }

unique_lock(mutex_type& __m, try_to_lock_t)
: _M_device(std::__addressof(__m)), _M_owns(_M_device->try_lock()) { }

unique_lock(mutex_type& __m, adopt_lock_t)
: _M_device(std::__addressof(__m)), _M_owns(true) { // XXX calling thread owns mutex }

void lock() {
    if (!_M_device)
        __throw_system_error(int(errc::operation_not_permitted));
    else if (_M_owns)
        __throw_system_error(int(errc::resource_deadlock_would_occur));
    else
    {
        _M_device->lock();
        _M_owns = true;
    }
}

void unlock() {
    if (!_M_owns)
        __throw_system_error(int(errc::operation_not_permitted));
    else if (_M_device)
    {
        _M_device->unlock();
        _M_owns = false;
    }
}

mutex_type* release() noexcept {
    mutex_type* __ret = _M_device;
    _M_device = 0;
    _M_owns = false;
    return __ret;
}