PracticeDev/study_cpp/mutex/demo4_lock_guard.cpp

49 lines
1.4 KiB
C++
Raw Normal View History

2022-12-20 17:31:11 +08:00
/*************************************************************************
> File Name : demo4_lock_guard.cpp
> Author : TL Song
> EMail : songtianlun@frytea.com
> Created Time : Tue Feb 9 11:43:19 2021
************************************************************************/
#include <iostream>
#include <thread>
#include <vector>
#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++) {
// std::lock_guard对象构造时自动调用mtx.lock()进行上锁
// std::lock_guard对象析构时自动调用mtx.unlock()释放锁
std::lock_guard<std::mutex> lk(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, 10000, 1);
std::thread t2(increase, 10000, 2);
t1.join();
t2.join();
std::cout << "counter:" << counter << std::endl;
return 0;
}