In C++14/C++17, a new kind of mutex, called shared mutex, is introduced.
Unlike other mutex types, a shared mutex has two levels of access:
- shared: several threads can share ownership of the same mutex.
- exclusive: only one thread can own the mutex.
This is useful in situations where we may allow multiple parallel readers or one writer to operate on a block of data.
As it is part of the future C++ standard, cppreference already has detailed documentation. Below is just a brief summary of the relevant classes and functions. (In CLUE++, we provide a C++11 implementation for these types, and the names are in the namespace clue
, instead of std
).
Here is an example of how shared_mutex can be used in practice.
using namespace clue;
class MyData {
std::vector<double> data_;
mutable shared_mutex mut_; // the mutex to protect data_;
public:
void write() {
unique_lock<shared_mutex> lk(mut_);
// ... write to data_ ...
}
void read() const {
shared_lock<shared_mutex> lk(mut_);
// ... read the data ...
}
};
// --- main program ---
MyData a;
std::thread t_write([&](){
a.write();
sleep_for_a_while();
});
std::thread t_read1([&](){
a.read();
});
std::thread t_read2([&](){
a.read();
});
// t_read1 and t_read2 can simultaneously read a,
// while t_write is not writing
The table below lists its member functions:
The class shared_timed_mutex
provides all the member funtions as in shared_mutex
. In addition, it provides the following members: