如何解决当现代C ++中需要通过getter作为shared_ptr返回受保护资源时,如何设计一次写入和多次读取?
我有一个作家线程在一个对象中写入地图,并且每个读者对象都在各自的线程中对地图执行只读操作,我的当前设计如下所示,
class MyClass {
private:
shared_ptr<map<int,int>> my_map;
mutable shared_mutex mu;
public:
void update_or_add(pair<int,int> entry);
shared_lock<shared_mutex> get_read_lock();
shared_ptr<const map<int,int>> get_map();
}
void MyClass::update_or_add(pair<int,int> entry) {
lock_guard<shared_mutex> locker(mu);
// do update on my_map
}
shared_lock<shared_mutex> MyClass::get_read_lock() {
shared_lock<shared_mutex> locker(mu);
return locker;
shared_ptr<const map<int,int>> MyClass::get_map() {
return my_map;
}
这是我的使用方式
//writer
//thread-1
MyClass obj;
while(true)
obj.update_or_add(entry);
//readers
//thread-2
shared_lock<shared_mutex> locker(obj.get_read_lock());
auto mymap = obj.get_map();
//some computation on mymap
....
//thread-n
shared_lock<shared_mutex> locker(obj.get_read_lock());
auto mymap = obj.get_map();
//some computation on mymap
关于上述内容,我有两个问题
- 这是使用shared_lock和shared_mutex的正确方法吗?
- 因为我想实现读取的并发,所以我返回了地图的指针并将其传递给其他对象进行计算,还有其他更好的设计吗?
谢谢。
解决方法
这是一个非常简单的共享资源:
template<class T>
struct shared_threadsafe {
template<class F>
auto read(F&& f)const{
auto l = lock(); // shared lock
return f(t); // const access
}
template<class F>
auto write(F&& f){
auto l = lock(); // exclusive lock
return f(t); // non-const access
}
// construct from a T
explicit shared_threadsafe( T in ):t(std::forward<T>(in)){}
// default construct
shared_threadsafe()=default;
shared_threadsafe(shared_threadsafe const&)=delete; // it can be written,but don't
shared_threadsafe& operator=(shared_threadsafe const&)=delete; // it can be written,but don't
~shared_threadsafe()=default;
private:
mutable std::shared_mutex m;
T t;
auto lock() const { return std::shared_lock{m}; }
auto lock() { return std::unique_lock{m}; }
}
它使用c++17非常简短。抱歉打错了。
您有一个:
shared_threadsafe<std::map<int,int>> bob;
作家线程:
bob.write([&](auto& bob){ bob.insert( p ); });
阅读器线程:
bob.read([&](auto& bob){
// cos=de that reads from the map `bob`
});
如果读取器线程具有const
引用或指针,则它们仅具有读取访问权限。
在实践中,我会考虑一些操作,使共享线程安全在某些类中是私有的,并且只公开那些操作。
通常公开完整的读/写锁定表明您的代码还不够高。基于锁的并发不能组成也不能很好地扩展。当您公开了在锁中运行任意代码的能力时,您鼓励进行组合,这是一场灾难。
我的共享线程安全是一个尝试的折衷方案,因为至少锁定代码仅写入一次且基于作用域。我将其隐藏,因为它仍然无法构成。
根据您的读/写操作和延迟的代价,选择争用版本的副本可能也是明智的选择。在此计划下,读取器将获得指向他们具有完全const访问权限的表的智能指针。如果存在争用,写程序将以写(cow)方式进行复制,否则进行快速更新。写时复制结果仅对写后出现的读者可见。
一个手写的(非标准)地图可以进行部分母牛更新,共享新旧读取之间未更改的表部分。
但是,此时,您开始考虑使用DB。也许您应该从哪个开始。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。