I have one writer thread write to a map in an object, and many reader object each in their own thread to perform read only on the map, my currrent design is like below,
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;
}
here is how I may use it
//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
I have two questions regard the above,
- is this the right way to use shared_lock and shared_mutex?
- because I want to achieve concurrency in read, so I have returned the map's pointer and passed it to other object to do the computation, is there any other better design?
Thanks.