【C++编程】shared_mutex
std::shared_mutex
1. 原型:
读写锁属性相关理论:【Liux系统编程】读写锁
1)测试用例:
#include <iostream>
#include <mutex>
#include <shared_mutex>
#include <thread>
class ThreadSafeCounter {
public:
ThreadSafeCounter() = default;
unsigned int get() const {
std::shared_lock lock(mutex_);
return value_;
}
unsigned int increment() {
std::unique_lock lock(mutex_);
return ++value_;
}
void reset() {
std::unique_lock lock(mutex_);
value_ = 0;
}
private:
mutable std::shared_mutex mutex_;
unsigned int value_ = 0;
};
int main() {
ThreadSafeCounter counter;
auto increment_and_print = [&counter]() {
for (int i = 0; i < 3; i++) {
std::cout << std::this_thread::get_id() << "-" << counter.increment() << std::endl;
}
};
std::thread thread1(increment_and_print);
std::thread thread2(increment_and_print);
thread1.join();
thread2.join();
}
输出:
2. 测试用例
2)测试用例