#include <mutex>
#include <condition_variable>
struct closed_exception{};
class ordered_lock
{
public:
explicit ordered_lock(bool openornot)
: m_cur_order(0)
, m_max_order(0)
, m_opened(openornot)
{}
void open()
{
std::unique_lock<std::mutex> lck(m_mtx);
m_opened = true;
}
void close()
{
std::unique_lock<std::mutex> lck(m_mtx);
m_opened = false;
m_cnd.notify_all();
}
void lock()
{
std::unique_lock<std::mutex> lck(m_mtx);
size_t order_number = m_max_order++;
m_cnd.wait(lck, [this, order_number]
{
if (!m_opened)
{
throw closed_exception();
}
return order_number == m_cur_order;
});
}
void unlock()
{
std::unique_lock<std::mutex> lck(m_mtx);
m_cur_order++;
m_cnd.notify_all();
}
private:
std::mutex m_mtx;
std::condition_variable m_cnd;
size_t m_cur_order{ 0 };
size_t m_max_order{ 0 };
bool m_opened { false };
};
C++11有序锁实现
最新推荐文章于 2024-10-07 19:17:25 发布