我有一组需要使用读取器/写入器锁保护的数据结构。我知道boost :: shared_lock,但是我想使用std :: mutex,std :: condition_variable和/或std :: atomic进行自定义实现,以便我更好地了解它的工作原理(并在以后进行调整) 。
每个数据结构(可移动但不可复制)都将从称为Commons的类继承,该类封装了锁定。我希望公共界面看起来像这样:
class Commons {
public:
void read_lock();
bool try_read_lock();
void read_unlock();
void write_lock();
bool try_write_lock();
void write_unlock();
};
...以便可以被某些人公开继承:
class DataStructure : public Commons {};
我正在编写科学代码,通常可以避免数据争用;这个锁主要是为了防止我以后可能犯的错误。因此,我的优先事项是低读取开销,因此我不会过多地妨碍正确运行的程序。每个线程可能将在其自己的CPU内核上运行。
您能给我看一下(密码可以吗)读/写锁?我现在所拥有的应该是防止作家饥饿的变体。到目前为止,我的主要问题一直是read_lock之间的差距,即检查读取是否可以安全地实际增加读者数量,然后write_lock知道要等待。
void Commons::write_lock() {
write_mutex.lock();
reading_mode.store(false);
while(readers.load() > 0) {}
}
void Commons::try_read_lock() {
if(reading_mode.load()) {
//if another thread calls write_lock here, bad things can happen
++readers;
return true;
} else return false;
}
我是多线程的新手,我真的很想了解它。在此先感谢您的帮助!
收到一只叮咚
犯罪嫌疑人X
相关分类