目录
2.4 lock_guard和unique_lock的使用和区别
mutex又称互斥量,C++ 11中与 mutex相关的类(包括锁类型)和函数都声明在头文件中,所以需要使用 std::mutex,就必须包含头文件。
C++11提供如下4种语义的互斥量(mutex)
- std::mutex,独占的互斥量,不能递归使用。
- std::time_mutex,带超时的独占互斥量,不能递归使用。
- std::recursive_mutex,递归互斥量,不带超时功能。
- std::recursive_timed_mutex,带超时的递归互斥量。
std::mutex 介绍
下面以 std::mutex 为例介绍 C++11 中的互斥量用法。
std::mutex 是C++11 中最基本的互斥量,std::mutex 对象提供了独占所有权的特性——即不支持递归地对 std::mutex 对象上锁,而 std::recursive_lock 则可以递归地对互斥量对象上锁。
std::mutex 的成员函数
1. 构造函数,std::mutex不允许拷贝构造,也不允许 move 拷贝,最初产生的 mutex 对象是处于unlocked 状态的。
2. lock(),调用线程将锁住该互斥量。线程调用该函数会发生下面 3 种情况:
(1). 如果该互斥量当前没有被锁住,则调用线程将该互斥量锁住,直到调用 unlock之前,该线程一直拥有该锁。
(2). 如果当前互斥量被其他线程锁住,则当前的调用线程被阻塞住。
(3). 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。
3. unlock(), 解锁,释放对互斥量的所有权。
4. try_lock(),尝试锁住互斥量,如果互斥量被其他线程占有,则当前线程也不会被阻塞。线程调用该函数也会出现下面 3 种情况,
(1). 如果当前互斥量没有被其他线程占有,则该线程锁住互斥量,直到该线程调用 unlock 释放互斥量。
(2). 如果当前互斥量被其他线程锁住,则当前调用线程返回false,而并不会被阻塞掉。
(3). 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。
- //mutex1
- //g++ mutex1.cpp -std=c++14 -lpthread
- #include <iostream> // std::cout
- #include <thread> // std::thread
- #include <mutex> // std::mutex
-
- volatile int counter(0); // non-atomic counter
- std::mutex mtx; // locks access to counter
-
- void increases_10k()
- {
- for (int i=0; i<10000; ++i) {
- // 1. 使用try_lock的情况
- // if (mtx.try_lock()) { // only increase if currently not locked:
- // ++counter;
- // mtx.unlock();
- // }
- // 2. 使用lock的情况
- {
- mtx.lock();
- ++counter;
- mtx.unlock();
- }
- }
- }
-
- int main()
- {
- std::thread threads[10];
- for (int i=0; i<10; ++i)
- threads[i] = std::thread(increases_10k);
-
- //等待线程退出
- for (auto& th : threads) th.join();
- std::cout << " successful increases of the counter " << counter << std::endl;
-
- return 0;
- }

递归锁允许同一个线程多次获取该互斥锁,可以用来解决同一线程需要多次获取互斥量时死锁的问题。
虽然递归锁能解决这种情况的死锁问题,但是尽量不要使用递归锁,主要原因如下:
1. 需要用到递归锁的多线程互斥处理本身就是可以简化的,允许递归很容易放纵复杂逻辑的产生,并且产生晦涩,当要使用递归锁的时候应该重新审视自己的代码是否一定要使用递归锁;
2. 递归锁比起非递归锁,效率会低;
3. 递归锁虽然允许同一个线程多次获得同一个互斥量,但可重复获得的最大次数并未具体说明,一旦超过一定的次数,再对lock进行调用就会抛出std::system错误。
- //死锁范例mutex2-dead-lock
- #include <iostream>
- #include <thread>
- #include <mutex>
-
- struct Complex
- {
- std::mutex mutex;
- int i;
-
- Complex() : i(0){}
-
- void mul(int x)
- {
- std::lock_guard<std::mutex> lock(mutex);
- i *= x;
- }
-
- void div(int x)
- {
- std::lock_guard<std::mutex> lock(mutex);
- i /= x;
- }
-
- void both(int x, int y)
- {
- //lock_guard 构造函数加锁, 析构函数释放锁
- std::lock_guard<std::mutex> lock(mutex);
- mul(x); // 获取不了锁
- div(y);
- }
-
- void init()
- {
- //lock_guard 构造函数加锁, 析构函数释放锁
- std::lock_guard<std::mutex> lock(mutex);
- sub_init();
- }
- void sub_init()
- {
- std::lock_guard<std::mutex> lock(mutex);
- }
- };
-
- int main(void)
- {
- Complex complex;
-
- complex.both(32, 23);
- std::cout << "main finish\n";
- return 0;
- }
运行后出现死锁的情况。在调用both时获取了互斥量,在调用mul时又要获取互斥量,但both的并没有释放,从而产生死锁。
- //递归锁recursive_mutex1
- #include
- #include
- #include
-
- struct Complex
- {
- std::recursive_mutex mutex;
- int i;
-
- Complex() : i(0){}
-
- void mul(int x)
- {
- std::lock_guard
lock(mutex) ; - i *= x;
- }
-
- void div(int x)
- {
- std::unique_lock
lock(mutex) ; - i /= x;
- }
-
- void both(int x, int y)
- {
- std::lock_guard
lock(mutex) ; - mul(x);
- div(y);
- }
- };
-
- int main(void)
- {
- Complex complex;
-
- complex.both(32, 23); //因为同一线程可以多次获取同一互斥量,不会发生死锁
-
- std::cout << "main finish\n";
- return 0;
- }

std::timed_mutex和std::recursive_timed_mutex
std::timed_mutex比std::mutex多了两个超时获取锁的接口:try_lock_for和try_lock_until。
try_lock_for:尝试获取互斥锁。阻塞直到指定timeout_duration时间过去或获得锁。
try_lock_until:尝试获取互斥锁。阻塞直到timeout_time达到指定或获得锁
- #include <iostream>
- #include <thread>
- #include <mutex>
- #include <chrono>
- std::timed_mutex mutex;
- void work() {
- std::chrono::milliseconds timeout(100);
- while (true) {
- if (mutex.try_lock_for(timeout)) {
- std::cout << std::this_thread::get_id() << ": do work with the mutex" << std::endl;
- std::chrono::milliseconds sleepDuration(250);
- std::this_thread::sleep_for(sleepDuration);
- mutex.unlock();
- std::this_thread::sleep_for(sleepDuration);
- } else {
- std::cout << std::this_thread::get_id() << ": do work without the mutex" << std::endl;
- std::chrono::milliseconds sleepDuration(100);
- std::this_thread::sleep_for(sleepDuration);
- }
- }
- }
- int main(void) {
- std::thread t1(work);
- std::thread t2(work);
- t1.join();
- t2.join();
- std::cout << "main finish\n";
- return 0;
- }

相对于手动lock和unlock,我们可以使用RAII(通过类的构造析构)来实现更好的编码方式。lock_guard和unique_lock ,在构造变量的时候,会去尝试上锁lock,在作用域消失,生命周期结束的时候会析构,这个时候就会解锁,unlock。
防止忘记释放锁

这里涉及到unique_lock,lock_guard的使用。lock_guard换成unique_lock是一样的。
- #include <iostream> // std::cout
- #include <thread> // std::thread
- #include <mutex> // std::mutex, std::lock_guard
- #include <stdexcept> // std::logic_error
-
- std::mutex mtx;
-
- void print_even (int x) {
- if (x%2==0) {
- std::cout << x << " is even\n";
- } else {
- //奇数throw
- throw (std::logic_error("not even"));
- }
- }
-
- void print_thread_id (int id) {
- try {
- //std::lock_guard<std::mutex> lck (mtx);
- std::unique_lock<std::mutex> lck (mtx);
- print_even(id);
- } catch (std::logic_error&) {
- //捕获异常
- std::cout << "[exception caught]\n";
- }
- }
-
- int main () {
- std::thread threads[10];
- // spawn 10 threads:
- for (int i=0; i<10; ++i) {
- threads[i] = std::thread(print_thread_id,i+1);
- }
-
- for (auto& th : threads) {
- th.join();
- }
- return 0;
- }

unique_lock与lock_guard都能实现自动加锁和解锁,但是前者更加灵活,能实现更多的功能。
unique_lock可以进行临时解锁和再上锁,如在构造对象之后使用lck.unlock()就可以进行解锁,lck.lock()进行上锁,而不必等到析构时自动解锁。
- #include <iostream>
- #include <deque>
- #include <thread>
- #include <mutex>
- #include <condition_variable>
- #include <unistd.h>
- std::deque<int> q;
- std::mutex mu;
- std::condition_variable cond;
- int count = 0;
- void fun1() {
- while (true) {
- std::unique_lock<std::mutex> locker(mu);
-
- q.push_front(count++);
-
- locker.unlock();
-
- cond.notify_one();
- sleep(1);
- }
- }
- void fun2() {
- while (true) {
- std::unique_lock<std::mutex> locker(mu);
-
- cond.wait(locker, []() {
- return !q.empty();
- });
- auto data = q.back();
- q.pop_back();
-
- //locker.unlock(); 可以调用也可以不调用,下一次循环之前的locker会析构,里面也会调用unlock
- std::cout << "thread2 get value form thread1: " << data << std::endl;
- }
- }
- int main() {
-
- std::thread t1(fun1);
- std::thread t2(fun2);
- t1.join();
- t2.join();
- return 0;
- }
条件变量的目的就是为了,在没有获得某种提醒时长时间休眠; 如果正常情况下, 我们需要一直循环(+sleep), 这样的问题就是CPU消耗+时延问题,条件变量的意思是在cond.wait这里一直休眠直到cond.notify_one唤醒才开始执行下一句; 还有cond.notify_all()接口用于唤醒所有等待的线程。
那么为什么必须使用unique_lock呢?
原因: 条件变量在wait时会进行unlock再进入休眠, lock_guard并无该操作接口
wait: 如果线程被唤醒或者超时那么会先进行lock获取锁, 再判断条件(传入的参数)是否成立, 如果成立则wait函数返回否则释放锁继续休眠
使用场景:需要结合notify+wait的场景使用unique_lock; 如果只是单纯的互斥使用lock_guard
lock_guard
1.std::lock_guard 在构造函数中进行加锁,析构函数中进行解锁。
2.锁在多线程编程中,使用较多,因此c++11提供了lock_guard模板类;在实际编程中,我们也可以根据自己的场景编写resource_guard RAII类,避免忘掉释放资源。
std::unique_lock
1. unique_lock 是通用互斥包装器,允许延迟锁定、锁定的有时限尝试、递归锁定、所有权转移和与条件变量一同使用。
2. unique_lock比lock_guard使用更加灵活,功能更加强大。
3. 使用unique_lock需要付出更多的时间、性能成本。