//
// Created by 张雪明 <zhangxueming@uniontech.com> on 2023/1/9.
//
#include "URReadWriteLock.h"

URRWLock::URRWLock()
{}

URRWLock::~URRWLock()
{}

void URRWLock::readLock()
{
    std::unique_lock<std::mutex> lock(m_mutex);
    m_readCond.wait(lock, std::bind(&URRWLock::isReadCond, this));
    ++m_readNum;
}

void URRWLock::writeLock()
{
    std::unique_lock<std::mutex> lock(m_mutex);
    m_writeCond.wait(lock, std::bind(&URRWLock::isWriteCond, this));
    m_isWrite = true;
}

void URRWLock::unReadLock()
{
    std::unique_lock<std::mutex> lock(m_mutex);
    --m_readNum;
    m_readCond.notify_all();
}

void URRWLock::unWriteLock()
{
    std::unique_lock<std::mutex> lock(m_mutex);
    m_isWrite = false;
    m_writeCond.notify_all();
}

bool URRWLock::isReadCond() const
{
    return m_isWrite == false;
}

bool URRWLock::isWriteCond() const
{
    return (!m_isWrite && 0 == m_readNum);
}
