互斥資源加鎖的實現方式
阿新 • • 發佈:2019-02-11
若使用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;
}