若使用mutex.lock()方法时std::cout出现异常,则会导致mutex无法释放。改用std::lock_guard可有效避免该情况发生。
#include <iostream>
#include <thread>
#include <string>
#include <mutex>
using namespace std;
std::mutex mu;
// 对资源加锁
/// 用lock若cout抛出异常则mu永远不会被释放
/// 用lock_guard析构时自动释放
void shared_print(std::string msg, int id) {
std::lock_guard<std::mutex> guard(mu); // 较好的方法
//mu.lock(); // 较差的方法
std::cout << msg << id << std::endl;
//mu.unlock();
}
void func_1() {
for (int i = 0; i > -100; --i) {
shared_print("from func_1 ", i);
}
}
class Fctor {
public:
void operator()(string& s) {
for (int i = 0; i > -10; --i) {
std::cout << "from t1: " << s << std::endl;
}
s = "factor";
}
};
int main() {
std::thread t1(func_1);
for (int i = 0; i < 100; ++i) {
shared_print("from main ", i);
}
t1.join();
return 0;
}
本文介绍了一种利用std::lock_guard替代mutex.lock()和unlock()来防止因std::cout异常导致mutex无法正常解锁的方法。通过示例代码展示了如何在函数中正确地使用std::lock_guard来保护临界区,确保即使在异常情况下也能自动释放锁。
760

被折叠的 条评论
为什么被折叠?



