What you are looking for is a multiple readers/single writer locking system. Unfortunately there is no built-in type for this (before C++14). If you can use boost, then you can go with boost's shared_mutex
If not, you're gonna have to do it yourself (read this other thread on SO). You can also use MS SRW lock, as stated by T.C. in his comment (see there).
Now, suppose you have your class shared_mutex
well defined and available. You just have to add one shared_mutex
object as an attribute to the class you want to protect. I would advise you to keep completely locking-free methods in your class and add wrappers around them, like this:
class Whatever;
class MyClass {
boost::shared_mutex mutex;
Whatever find_unlocked() {
whatever blob_blob;
blob_blob = do_whatever_work_find_does();
return blob_blob;
}
void write_smth_unlocked() {
do_something_that_needs_writing_to_MyClass();
}
public:
Whatever find() {
Whatever blob;
mutex.lock_shared(); // Locks for reading (shared ownership on the mutex)
blob = find_unlocked();
mutex.unlock_shared();
return blob;
}
void write_smth() {
mutex.lock(); // Locks for writing (exclusive ownership on the mutex)
write_smth_unlocked();
mutex.unlock();
}
};
Doing so will grant you the ability to reuse the operations you define in new features for the class while still being able to protect the whole new operations through the locking system.
In the end you would have two methods for any operation you define:
- A private (or protected) method:
operation_unlocked()
- A public one:
operation()
which uses the shared_mutex
.