【C++ 17 | thread】shared_mutex
std::shared_mutex
1. 原型:
读写锁属性相关理论:
1)测试用例:
1 #include2 #include 3 #include 4 #include 5 6 class ThreadSafeCounter { 7 public: 8 ThreadSafeCounter() = default; 9 10 unsigned int get() const { 11 std::shared_lock lock(mutex_); 12 return value_; 13 } 14 15 unsigned int increment() { 16 std::unique_lock lock(mutex_); 17 return ++value_; 18 } 19 20 void reset() { 21 std::unique_lock lock(mutex_); 22 value_ = 0; 23 } 24 25 private: 26 mutable std::shared_mutex mutex_; 27 unsigned int value_ = 0; 28 }; 29 30 int main() { 31 ThreadSafeCounter counter; 32 33 auto increment_and_print = [&counter]() { 34 for (int i = 0; i < 3; i++) { 35 std::cout << std::this_thread::get_id() << "-" << counter.increment() << std::endl; 36 } 37 }; 38 39 std::thread thread1(increment_and_print); 40 std::thread thread2(increment_and_print); 41 42 thread1.join(); 43 thread2.join(); 44 }
输出:
2. 测试用例
1 #include2 #include 3 #include 4 #include 5 6 std::shared_mutex g_mutex; 7 std::string g_str; 8 9 void readLoop() { 10 while (true) { 11 std::this_thread::sleep_for(chrono::milliseconds(100)); 12 g_mutex.lock_shared(); 13 std::cout << g_str; 14 g_mutex.unlock_shared(); 15 } 16 } 17 18 void writeLoop() { 19 int number = 0; 20 while (true) { 21 stgd::this_thread::sleep_for(chrono::milliseconds(100)); 22 g_mutex.lock(); 23 g_str = to_string(number++) + "\n"; 24 g_mutex.unlock(); 25 } 26 } 27 28 int main() { 29 std::thread t1(writeLoop); 30 std::thread t2(readLoop); 31 std::thread t3(readLoop); 32 33 t1.join(); 34 t2.join(); 35 t3.join(); 36 }
2)测试用例