问题
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?
回答1:
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
.
回答2:
It’s not part of C++ standard yet, but you can find implementation example in boost.
template<typename SharedMutex>
class shared_lock_guard
{
private:
SharedMutex& m;
public:
typedef SharedMutex mutex_type;
explicit shared_lock_guard(SharedMutex& m_):
m(m_)
{
m.lock_shared();
}
shared_lock_guard(SharedMutex& m_,adopt_lock_t):
m(m_)
{}
~shared_lock_guard()
{
m.unlock_shared();
}
};
It requires mutex class conforming to SharedMutex concept though; std::shared_mutex is part of proposed C++17 standard and boost had one already for some time: boost::shared_mutex.
来源:https://stackoverflow.com/questions/39185420/is-there-a-shared-lock-guard-and-if-not-what-would-it-look-like