C++14您可以使用std ::shared_lock和std::unique_lock来实现读/写锁定:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:如果有C++17,则可以使用std::shared_mutexfor mutex_type。