C++ 多线程同步之互斥锁(mutex)实战
C++ 多线程同步之互斥锁(mutex)实战
💡 学习目标:掌握 C++ 标准库中互斥锁的基本用法,理解多线程同步的核心原理,能够解决多线程环境下的资源竞争问题。
💡 学习重点:std::mutex 与 std::lock_guard 的使用、死锁的产生原因及规避方法、实际场景中的同步案例实现。
48.1 多线程同步的必要性
在多线程编程中,当多个线程同时访问共享资源时,会出现资源竞争问题。
例如两个线程同时对同一个变量进行读写操作,会导致最终结果与预期不符。
这种问题被称为线程安全问题,而解决该问题的核心就是线程同步。
⚠️ 注意事项:线程不同步会引发数据竞争,造成程序运行结果不可预测,甚至导致程序崩溃。
举个简单的反例,两个线程同时对全局变量 count 进行自增操作:
#include<iostream>#include<thread>usingnamespace std;int count =0;voidincrement(){for(int i =0; i <100000;++i){ count++;// 非原子操作,存在数据竞争}}intmain(){ thread t1(increment); thread t2(increment); t1.join(); t2.join(); cout <<"最终 count 值:"<< count << endl;return0;}运行该程序会发现,最终 count 的值大概率小于 200000。
这就是因为 count++ 不是原子操作,被两个线程交替执行打乱了执行步骤。
48.2 C++ 标准库中的互斥锁
C++11 及以后的标准库提供了 <mutex> 头文件,封装了多种互斥锁相关的类。
最基础且常用的就是 std::mutex。
48.2.1 std::mutex 的核心接口
lock():获取互斥锁。如果锁已被其他线程占用,当前线程会阻塞等待。unlock():释放互斥锁。必须与lock()成对使用。try_lock():尝试获取互斥锁。如果获取失败,不会阻塞,直接返回false。
48.2.2 std::lock_guard:自动管理锁的生命周期
直接使用 lock() 和 unlock() 容易出现遗漏解锁的情况。
比如程序抛出异常时,unlock() 可能无法执行,导致死锁。std::lock_guard 基于RAII 机制实现,可以自动在构造时加锁,析构时解锁。
✅ 核心结论:实际开发中优先使用 std::lock_guard,而非手动调用 lock()/unlock()。
48.3 互斥锁实战:解决数据竞争问题
我们使用 std::mutex 和 std::lock_guard 改造 48.1 节的反例:
#include<iostream>#include<thread>#include<mutex>usingnamespace std;int count =0; mutex mtx;// 定义全局互斥锁voidincrement(){for(int i =0; i <100000;++i){ lock_guard<mutex>lock(mtx);// 自动加锁 count++;// 临界区代码,此时只有一个线程能执行}// lock_guard 析构,自动解锁}intmain(){ thread t1(increment); thread t2(increment); t1.join(); t2.join(); cout <<"最终 count 值:"<< count << endl;return0;}运行该程序,最终 count 的值稳定等于 200000。
这说明互斥锁成功保护了临界区代码,避免了数据竞争。
48.3.1 关键概念解释
- 临界区:需要被保护的、不能被多个线程同时执行的代码段。
上例中count++就是临界区。 - 互斥锁的作用:保证同一时刻只有一个线程能进入临界区。
48.4 死锁的产生与规避
💡 死锁:多个线程互相持有对方需要的锁,导致所有线程都无法继续执行的状态。
48.4.1 死锁的四个必要条件
- 互斥条件:资源只能被一个线程占用。
- 请求与保持条件:线程持有一个资源的同时,请求其他线程持有的资源。
- 不可剥夺条件:线程已持有的资源不能被其他线程强制夺走。
- 循环等待条件:多个线程形成首尾相接的循环等待资源关系。
48.4.2 死锁的示例
两个线程分别持有一个锁,同时请求对方的锁:
#include<iostream>#include<thread>#include<mutex>usingnamespace std; mutex mtx1, mtx2;voidthread1(){ mtx1.lock(); this_thread::sleep_for(chrono::milliseconds(100));// 确保 thread2 先拿到 mtx2 mtx2.lock();// 等待 mtx2,此时 thread2 持有 mtx2 并等待 mtx1 cout <<"thread1 执行完毕"<< endl; mtx2.unlock(); mtx1.unlock();}voidthread2(){ mtx2.lock(); this_thread::sleep_for(chrono::milliseconds(100));// 确保 thread1 先拿到 mtx1 mtx1.lock();// 等待 mtx1,此时 thread1 持有 mtx1 并等待 mtx2 cout <<"thread2 执行完毕"<< endl; mtx1.unlock(); mtx2.unlock();}intmain(){ thread t1(thread1); thread t2(thread2); t1.join(); t2.join();return0;}运行该程序,两个线程会互相等待,陷入死锁状态,无法输出任何内容。
48.4.3 规避死锁的常用方法
- 固定锁的获取顺序:所有线程按照相同的顺序获取锁。
比如上例中,让两个线程都先获取mtx1,再获取mtx2。 - 使用
std::lock同时获取多个锁:std::lock可以一次性获取多个互斥锁,避免循环等待。 - 使用带超时的锁尝试:通过
try_lock()或std::timed_mutex,在超时后放弃获取锁,避免永久阻塞。
48.5 实战案例:多线程售票系统
模拟一个售票系统,多个窗口同时售票,使用互斥锁保证票数不会出现负数或重复售票的情况。
#include<iostream>#include<thread>#include<mutex>#include<vector>usingnamespace std;int tickets =100;// 总票数 mutex mtx;// 售票函数voidsell_tickets(int window_id){while(true){ lock_guard<mutex>lock(mtx);if(tickets >0){ cout <<"窗口"<< window_id <<"售出第"<< tickets <<"张票"<< endl; tickets--; this_thread::sleep_for(chrono::milliseconds(50));// 模拟售票耗时}else{break;}} cout <<"窗口"<< window_id <<"售票结束"<< endl;}intmain(){ vector<thread> windows;// 创建 5 个售票窗口for(int i =1; i <=5;++i){ windows.emplace_back(sell_tickets, i);}// 等待所有窗口售票结束for(auto& t : windows){ t.join();} cout <<"所有票已售罄"<< endl;return0;}✅ 运行效果:5 个窗口有序售票,最终票数从 100 递减到 0,不会出现重复售票或票数为负的情况。
48.6 本章小结
- 多线程访问共享资源时必须进行同步,否则会出现数据竞争问题。
std::mutex是 C++ 最基础的互斥锁,搭配std::lock_guard可以安全地管理锁的生命周期。- 死锁由四个必要条件引发,通过固定锁顺序、使用
std::lock等方法可以有效规避。 - 互斥锁的核心是保护临界区,确保同一时刻只有一个线程能执行临界区代码。