前提:
在上一節(jié)中,我們使用了mutex的lock函數(shù)和unlock函數(shù)處理共享資源問題
這一節(jié),我們學習使用 lock_guard來處理 共享資源問題。
lock_guard是啥?
是個類模版,這個類模版只能對mutex類型進行構造
例子:
lock_guard<mutex> mylock_guard(mymutex);
lock_guard的優(yōu)點:
優(yōu)點類似于智能指針,
當我們實例化一個 lock_guard后,不需要unlock()
lock_guard<mutex> mylock_guard(mymutex);
lock_guard工作原理
lock_guard是個類,那么就有構造函數(shù)和析構函數(shù)。
lock_guard的構造函數(shù)里面 執(zhí)行了 mutex::lock();
lock_guard的析構函數(shù)里面 指向了 mutex::unlock();
這也是lock_guard類只用 實例化出來,就不會unlock()的原因,因為當lock_guard 對象析構的時候,會自動的unlock();
這也意味著在實現(xiàn)時,要特別注意lock_guard 對象是什么時候析構的。必要的時候,可以用{}包裝起來。文章來源:http://www.zghlxwxcb.cn/news/detail-799064.html
lock_guard 實例
改動代碼如下:文章來源地址http://www.zghlxwxcb.cn/news/detail-799064.html
class Teacher166 {
public:
//共享數(shù)據(jù) 存在list中
list<int> msgListQueue;
mutex mymutex;
int readcount = 0;//記錄已經(jīng)讀取了多少個。
public:
//讀取 共享數(shù)據(jù)的線程方法
void readfunc() {
while (true) {
//只要不為空,就可以讀取數(shù)據(jù)
if (readcount >= 2000) {
break;
}
lock_guard<mutex> mylock_guard(mymutex);//mylock_guard在這里創(chuàng)建出來,在mylock_guard的構造函數(shù)中,就已經(jīng)對mymutex進行了lock()操作,等到mylock_guard的生命周期結(jié)束后會析構,這時候會調(diào)用mymutex的unlock()函數(shù)
if (!msgListQueue.empty()) {
int readvalue = msgListQueue.front();//每次都讀取第一個
cout << "讀取到的值為" << readvalue << " readcount = " << readcount << endl;
msgListQueue.pop_front();//刪除第一個元素
readcount++;
}
else {
cout << "沒有讀取到值" << endl;
}
}
}
//寫入 共享數(shù)據(jù)的線程方法
void writefunc() {
for (size_t i = 0; i < 1000; i++)
{
lock_guard<mutex> mylock_guard(mymutex);//mylock_guard在這里創(chuàng)建出來,在mylock_guard的構造函數(shù)中,就已經(jīng)對mymutex進行了lock()操作,等到mylock_guard的生命周期結(jié)束后會析構,這時候會調(diào)用mymutex的unlock()函數(shù),實際上這里實例化對象 lock_guard<mutex> 不管名字是啥,只要里面參數(shù)是 mymutex就可以了,也就是說:只要是同一個 mutex
msgListQueue.push_back(i);//每次都寫到末尾
cout << "寫入元素的值為" << i << endl;
}
}
public:
Teacher166() {
cout << "Teacher166 構造方法 this = " << this << endl;
}
Teacher166(const Teacher166 & obj) {
cout << "Teacher166 copy 構造方法 this = " << this << " obj = " << &obj << endl;
}
~Teacher166() {
cout << "Teacher166 析構函數(shù) this = " << this << endl;
}
};
void main() {
cout << "=========================" << endl;
Teacher166 tea1;
thread readthread1(&Teacher166::readfunc, &tea1);
thread writethread1(&Teacher166::writefunc, &tea1);
//thread 的構造方法第二個參數(shù) 可以是地址,如果是地址,那么 readthread1 和 writethread1的傳遞就是同一個 teacher
thread readthread2(&Teacher166::readfunc, &tea1);
thread writethread2(&Teacher166::writefunc, &tea1);
readthread1.join();
readthread2.join();
writethread1.join();
writethread2.join();
}
到了這里,關于50 C++ 多個線程共享資源問題fix方案二 ----- lock_guard類的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!