std::lock_guard和std::mutex 的用法
功能介紹
二者均屬於C++11的特性:
-
std::mutex屬於C++11中對操作系統鎖的最常用的一種封裝,可以通過lock、unlock等接口實現對數據的鎖定保護。
-
std::lock_guard是C++11提供的鎖管理器,可以管理std::mutex,也可以管理其他常見類型的鎖。
std::lock_guard的對鎖的管理屬於RAII風格用法(Resource Acquisition Is Initialization),在構造函數中自動綁定它的互斥體並加鎖,在析構函數中解鎖,大大減少了死鎖的風險。
代碼示例
#include <iostream>
#include <mutex>
#include <thread>
int loop_cnt = 10000000;
class Widget
{
public:
Widget() = default;
~Widget() = default;
void addCnt()
{
std::lock_guard<std::mutex> cLockGurad(lock_); //構造時加鎖,析構時解鎖
// lock_.lock(); //不使用lock_guard時的寫法
cnt++;
// lock_.unlock();//不使用lock_guard時的寫法,萬一沒有解鎖就會死鎖。
}
int cnt = 0;
private:
std::mutex lock_;
};
void ThreadMain1(Widget *pw)
{
std::cout << "thread 1 begin." << "\n";
for (int i = 0; i < loop_cnt; i++)
pw->addCnt();
std::cout << "thread 1 end." << "\n";
}
void ThreadMain2(Widget *pw)
{
std::cout << "thread 2 begin." << "\n";
for (int i = 0; i < loop_cnt; i++)
pw->addCnt();
std::cout << "thread 2 end." << "\n";
}
int main()
{
Widget *pw = new Widget();
std::thread t1(&ThreadMain1, pw);
std::thread t2(&ThreadMain2, pw);
t1.join();
t2.join();
std::cout << "cnt =" << pw->cnt << std::endl;
return 0;
}