一、互斥量
1. 为什么需要互斥量
互斥就是保证资源同一时刻只能被一个线程使用;如果A线程在执行计算式A的时候,某个量被B线程改掉了,这可能会出现问题,于是要求资源互斥,几个线程间互不干扰。
例1:无锁
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
int counter = 0;
void increase(int time) {
for (int i = 0; i < time; i++) {
// 当前线程休眠1毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(1));
counter++;
}
}
int main(int argc, char** argv) {
std::thread t1(increase, 100);
std::thread t2(increase, 100);
t1.join();
t2.join();
std::cout << "counter:" << counter << std::endl;
return 0;
}
打印结果:
原因是:自增操作"counter++"不是原子操作,而是由多条汇编指令完成的,因此多个线程对同一个变量进行读写操作就会出现不可预期的操作。比如:假定counter当前值为10,线程1读取到了10,线程2也读取到了10,分别执行自增操作,线程1和线程2分别将自增的结果写回counter,不管写入的顺序如何,counter都会是11,但是线程1和线程2分别执行了一次自增操作,与我们所期望的结果12不符。
为了应对这种情况,c++11中出现了std::atomic
和std::mutex
。
2. std::mutex
互斥量 Mutex是一种同步机制,是多线程编程中常用的一种工具,用于确保在任意给定时间只有一个线程可以访问共享资源,从而避免多个线程同时修改数据造成的竞态条件和数据不一致的问题。
std::mutex
是 C++11 中最基本的互斥量,一个线程将mutex锁住时,其它的线程就不能操作mutex,直到这个线程将mutex解锁。
在例1中使用std::mutex
,对于线程1或者线程2,如果想访问counter,首先要进行"加锁"操作,如果加锁成功,则进行counter的读写,读写操作完成后释放锁; 如果“加锁”不成功,则线程阻塞,直到加锁成功。
例2:加锁
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
int counter = 0;
std::mutex mtx;
void increase(int time) {
for (int i = 0; i < time; i++) {
mtx.lock();
// 当前线程休眠1毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(1));
counter++;
mtx.unlock();
}
}
int main(int argc, char** argv) {
std::thread t1(increase, 100);
std::thread t2(increase, 100);
t1.join();
t2.join();
std::cout << "counter:" << counter << std::endl;
return 0;
}
打印结果:
std::mutex()的总结:
- 对于
std::mutex
对象,任意时刻最多允许一个线程对其进行上锁 mtx.lock()
:调用该函数的线程尝试加锁:如果该互斥量当前未上锁,则本线程将该互斥量锁住,直到调用unlock()之前,本线程一直拥有该锁;如果该互斥量当前被其他线程锁住,则本线程被阻塞,直至该互斥量被其他线程解锁,此时本线程将该互斥量锁住,直到调用unlock()之前,本线程一直拥有该锁。如果上锁成功,则执行后面的操作,操作完成后要调用mtx.unlock()
释放锁,否则会导致死锁的产生mtx.try_lock()
:“尝试上锁”,与mtx.lock()的不同点在于:如果上锁不成功,当前线程不阻塞。
死锁的必要条件:
- 互斥(资源同一时刻只能被一个进程使用)
- 请求并保持(进程在请资源时,不释放自己已经占有的资源)
- 不剥夺(进程已经获得的资源,在进程使用完前,不能强制剥夺)
- 循环等待(进程间形成环状的资源循环等待关系)
3. lock_guard()
仅使用std::mutex
有时候会发生死锁:假设线程1上锁成功,线程2上锁等待,但是线程1上锁成功后,抛出异常并退出,没有来得及释放锁,导致线程2“永久的等待下去”,此时就发生了死锁。
例3:抛出异常并退出导致死锁
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <stdexcept>
int counter = 0;
std::mutex mtx; // 保护counter
void increase_proxy(int time, int id) {
for (int i = 0; i < time; i++) {
mtx.lock();
// 线程1上锁成功后,抛出异常:未释放锁
if (id == 1) {
throw std::runtime_error("throw excption....");
}
// 当前线程休眠1毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(1));
counter++;
mtx.unlock();
}
}
void increase(int time, int id) {
try {
increase_proxy(time, id);
}
catch (const std::exception& e){
std::cout << "id:" << id << ", " << e.what() << std::endl;
}
}
int main(int argc, char** argv) {
std::thread t1(increase, 100, 1);
std::thread t2(increase, 100, 2);
t1.join();
t2.join();
std::cout << "counter:" << counter << std::endl;
return 0;
}
打印结果:发生了死锁
使用局部std::lock_guard()
避免该情况,std::lock_guard()
只有构造函数和析构函数,当调用构造函数时,会自动调用传入的对象的lock()
函数,而当离开作用域调用析构函数时,自动调用unlock()
函数。通过使用{}来调整作用域范围,使得互斥量mtx在合适的地方被解锁。
例4:使用lock_guard避免死锁
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
int counter = 0;
std::mutex mtx; // 保护counter
void increase_proxy(int time, int id) {
for (int i = 0; i < time; i++) {
//std::lock_guard对象构造时,自动调用mtx.lock()进行上锁
//std::lock_guard对象析构时,自动调用mtx.unlock()进行解锁
std::lock_guard<std::mutex> l(mtx);
// 线程1上锁成功后,抛出异常:未释放锁
if (id == 1) {
throw std::runtime_error("throw excption....");
}
// 当前线程休眠1毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(1));
counter++;
}
}
void increase(int time, int id) {
try {
increase_proxy(time, id);
}
catch (const std::exception& e) {
std::cout << "id:" << id << ", " << e.what() << std::endl;
}
}
int main(int argc, char** argv) {
std::thread t1(increase, 100, 1);
std::thread t2(increase, 100, 2);
t1.join();
t2.join();
std::cout << "counter:" << counter << std::endl;
return 0;
}
打印结果:
使用std::mutex和std::lock_guard搭配使用,避免死锁的发生。
std::lock_gurad()
也可以传入两个参数,第二个参数为adopt_lock标识时,表示构造函数中不再进行互斥量锁定,因此此时需要提前手动锁定。
mtx.lock();
std::lock_guard<std::mutex> l(mtx, std::adopt_lock);
4. unique_lock()
std::unique_lock
与lock_guard
类似,但std::unique_lock
用法更加丰富,同时支持std::lock_guard()
的原有功能。
- 使用
std::lock_guard
后不能手动lock()与手动unlock();使用std::unique_lock
后可以手动lock()与手动unlock() std::unique_lock
的第二个参数,除了可以是adopt_lock
,还可以是try_to_lock
与defer_lock
- try_to_lock: 尝试去锁定,得保证锁处于unlock的状态,然后尝试现在能不能获得锁;尝试用mutx的lock()去锁定这个mutex,但如果没有锁定成功,会立即返回,不会阻塞在那里,并继续往下执行;
- defer_lock:转移
std::unique_lock的所有权
,std::mutex
对象的所有权不需要手动转移给std::unique_lock
,std::unique_lock
对象实例化后会直接接管std::mutex
5. atomic
mutex很好地解决了多线程资源争抢的问题,但它也有缺点:速度太慢了。
每次循环都要加锁、解锁,这样会浪费很多的时间,atomic就能够解决这个问题。
以例2基础,只需要将int类型转为std::atomic_int
类型,std::atomic_int
是std::atomic<int>
的别名。atomic,本意为原子,原子操作是最小的且不可并行化的操作,这就意味着即使是多线程,也要像同步进行一样同步操作atomic对象,从而省去了mutex上锁、解锁的时间消耗。
例5:atomic
#include <iostream>
#include <thread>
#include <atomic>
#include <chrono>
std::atomic_int counter = 0;
void increase(int time) {
for (int i = 0; i < time; i++) {
// 当前线程休眠1毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(1));
counter++;
}
}
int main(int argc, char** argv) {
std::thread t1(increase, 100);
std::thread t2(increase, 100);
t1.join();
t2.join();
std::cout << "counter:" << counter << std::endl;
return 0;
}
打印结果: