在上一章中,我们看到了lock_guard。在本章中,我们将学习独特的锁。
唯一锁是可从C ++ 11获得的类。
唯一锁是互斥锁的包装。它将拥有传递给唯一锁的互斥锁。
独特的锁具有以下功能:
1.唯一锁可以具有不同的锁定策略。
2.可以使用基于时间的锁定[try_lock_for,try_lock_until]。
3.还提供递归锁定。
4.使用移动转移锁所有权。
5.它还支持条件变量。
以下是唯一锁定中可用的一些锁定策略。
1. defer_lock:它不会获得互斥体的所有权。
2. try_to_lock:它将尝试获取互斥锁的所有权而不会阻塞。
3. 采用锁定:将假定调用线程已获得互斥体的所有权。
当你不穿’如果指定锁定策略,它将仅锁定互斥锁。
关于unique_lock要记住的重要一点是,当互斥锁超出范围时,它将自动解锁互斥锁。
现在,借助示例帮助我们了解unique_lock:
示例1:一个简单的unique_lock
#include <iostream> // std::cout #include <chrono> // std::chrono::milliseconds #include <thread> // std::thread #include <mutex> // std::timed_mutex // for more tutorials 上 C, C ++, DS visit www.ProDeveloperTutorial.com using namespace std; std::mutex mtx; int count_num = 0; void increment_fun (int thread_num, int val) { unique_lock<mutex> lock(mtx); // locking mtx mutex for (int i = 0; i < val; ++i) { cout<<"Thread "<<thread_num<<" count = "<<count_num++<<endl; } //mtx.unlock();// no need to call unlock } int main () { std::thread t1 (increment_fun, 1, 5); std::thread t2 (increment_fun, 2, 6); t1.join(); t2.join(); return 0; }
输出:
Thread 1 count = 0 Thread 1 count = 1 Thread 1 count = 2 Thread 1 count = 3 Thread 1 count = 4 Thread 2 count = 5 Thread 2 count = 6 Thread 2 count = 7 Thread 2 count = 8 Thread 2 count = 9 Thread 2 count = 10
示例2:带有defer_lock标志的unique_lock
#include <iostream> // std::cout #include <chrono> // std::chrono::milliseconds #include <thread> // std::thread #include <mutex> // std::timed_mutex // for more tutorials 上 C, C ++, DS visit www.ProDeveloperTutorial.com using namespace std; std::mutex mtx; int count_num = 0; void increment_fun (int thread_num, int val) { // as we are using defer_lock flag, it will not lock the mutex "mtx" unique_lock<mutex> lock(mtx, defer_lock); //hence you explicitly need to call the lock 上 the mutex lock.lock(); for (int i = 0; i < val; ++i) { cout<<"Thread "<<thread_num<<" count = "<<count_num++<<endl; } //mtx.unlock();// no need to call unlock, as we are using unique_lock } int main () { std::thread t1 (increment_fun, 1, 5); std::thread t2 (increment_fun, 2, 6); t1.join(); t2.join(); return 0; }
输出:
Thread 1 count = 0 Thread 1 count = 1 Thread 1 count = 2 Thread 1 count = 3 Thread 1 count = 4 Thread 2 count = 5 Thread 2 count = 6 Thread 2 count = 7 Thread 2 count = 8 Thread 2 count = 9 Thread 2 count = 10
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |