1 Star 2 Fork 0

InnovatorNZ/CppGCPtr

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
WeakSpinReadWriteLock.h 1.08 KB
一键复制 编辑 原始数据 按行查看 历史
#pragma once
#include <atomic>
#include <thread>
#include "IReadWriteLock.h"
class WeakSpinReadWriteLock : public IReadWriteLock {
private:
std::atomic<int> read_cnt;
std::atomic<bool> write_flag;
public:
WeakSpinReadWriteLock() : read_cnt(0), write_flag(false) {
}
void lockRead() override {
while (write_flag.load(std::memory_order_acquire)) {}
read_cnt.fetch_add(1, std::memory_order_release);
}
void unlockRead() override {
read_cnt.fetch_add(-1, std::memory_order_release);
}
void lockWrite(bool yield) override {
while (true) {
int c_read_cnt = read_cnt.load(std::memory_order_acquire);
bool c_write_flag = write_flag.load(std::memory_order_acquire);
if (c_read_cnt || c_write_flag) {
if (yield) std::this_thread::yield();
continue;
}
if (write_flag.compare_exchange_weak(c_write_flag, true, std::memory_order_release)) {
while (read_cnt.load(std::memory_order_acquire) != 0) {}
break;
}
}
}
void lockWrite() override {
lockWrite(false);
}
void unlockWrite() override {
write_flag.store(false, std::memory_order_release);
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/innovatornz/CppGCPtr.git
git@gitee.com:innovatornz/CppGCPtr.git
innovatornz
CppGCPtr
CppGCPtr
master

搜索帮助