参考网上资料,实现了一个读写锁,写优先。使用起来也很简单。
使用:
//先定义一个全局锁对象
tg_rwlock g_rwlock;
void test()
{
{
tg_rwlock::read_guard(g_rwlock);
//读..........
}
{
tg_rwlock::write_guard(g_rwlock);
//写..........
}
}
tg_rwlock.h
#ifndef TG_RWLOCK_H
#define TG_RWLOCK_H
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <memory>
class tg_rwguard;
class tg_rwlock
{
friend tg_rwguard;
private:
std::atomic<uint32_t> _read_cnt{ 0 };
std::atomic<uint32_t> _write_cnt{ 0 };
std::atomic<bool> _is_writing{false};
std::mutex _mutex;
std::condition_variable _read_cond;
std::condition_variable _write_cond;
public:
tg_rwlock() = default;
~tg_rwlock() = default;
static std::shared_ptr<tg_rwguard> read_guard(tg_