In a mutithreading server, one thread(writer) update data periodically from a database and other thread(readers) process user's request with this data.
I try to use a read/write lock to meet this request, but the performance is so bad, so it's needed to find something else.
I read from https://en.cppreference.com/w/cpp/memory/shared_ptr, it's says:
All member functions (including copy constructor and copy assignment) can be called by multiple threads on different instances of shared_ptr without additional synchronization even if these instances are copies and share ownership of the same object.
Then after some research, I use to std::shared_ptr to do it. The code is like something below.
// this class is singleton
class DataManager{
public:
// all the reader thread use this method to get data and release shared_ptr
// at the end of user's request
std::shared_ptr<Data> get_main_ptr(){
return _main_data;
}
private:
// data1
std::shared_ptr<Data> _main_data;
// data2
std::shared_ptr<Data> _back_data;
// read database, write data in to _data
void update_data(std::shared_ptr<Data> _data);
// this function called at a separate thread every 10 min
bool reload_data(){
// write data in back pointer
update_data(_back_data);
//save the _main_data
std::shared_ptr<Data> old_ptr = _main_data;
//exchange pointer, reader thread hold the copy of _main_data
_main_data = _back_data;
// wait until reader threads release all copy of _main_data
while(old_ptr.use_count() != 1) {
sleep(5);
}
// clear the data
old_ptr->clear();
_back_data = old_ptr;
return;
}
}
This method seems worked in production environment. but I'm not quite sure and don't understand the thread safe level of shared_ptr. Is there problem in this method? Or other suggestions to meet my request