I wanted to use a std::mutex
in my class, and noticed that it isn't copyable. I'm at the bottom level of my library here, so it seems like a terrible idea to have this behaviour.
I used std::lock_guard
on the std::mutex
, but there doesn't seem to be a shared_lock_guard
, which would be preferable to provide write-locks-exclusively behaviour. Is this an oversight or trivial to implement myself?
With C++14
You can use a std::shared_lock and a std::unique_lock to implement read/write locking:
class lockable
{
public:
using mutex_type = std::shared_timed_mutex;
using read_lock = std::shared_lock<mutex_type>;
using write_lock = std::unique_lock<mutex_type>;
private:
mutable mutex_type mtx;
int data = 0;
public:
// returns a scoped lock that allows multiple
// readers but excludes writers
read_lock lock_for_reading() { return read_lock(mtx); }
// returns a scoped lock that allows only
// one writer and no one else
write_lock lock_for_writing() { return write_lock(mtx); }
int read_data() const { return data; }
void write_data(int data) { this->data = data; }
};
int main()
{
lockable obj;
{
// reading here
auto lock = obj.lock_for_reading(); // scoped lock
std::cout << obj.read_data() << '\n';
}
{
// writing here
auto lock = obj.lock_for_writing(); // scoped lock
obj.write_data(7);
}
}
Note: If you have C++17
, then you can use std::shared_mutex
for mutex_type
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With