C++中lock_guard的学习
生活随笔
收集整理的這篇文章主要介紹了
C++中lock_guard的学习
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
lock_guard
- 鎖守衛(wèi)是一個管理mutex對象的對象,使其始終處于鎖定狀態(tài)。
- 在構(gòu)造時,mutex對象被調(diào)用線程鎖定,在銷毀時,mutex被解鎖。這是最簡單的鎖,作為一個自動持續(xù)時間的對象,它的作用特別大,可以持續(xù)到上下文結(jié)束。通過這種方式,它可以保證mutex對象在發(fā)生異常時被正確解鎖。
- 但請注意,lock_guard對象并不以任何方式管理mutex對象的壽命:mutex對象的持續(xù)時間至少應(yīng)延長到鎖定它的lock_guard被破壞為止。
代碼
// lock_guard example #include <iostream> // std::cout #include <thread> // std::thread #include <mutex> // std::mutex, std::lock_guard #include <stdexcept> // std::logic_errorstd::mutex mtx;void print_even (int x) {if (x%2==0) std::cout << x << " is even\n";else throw (std::logic_error("not even")); }void print_thread_id (int id) {try {// using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:std::lock_guard<std::mutex> lck (mtx);print_even(id);}catch (std::logic_error&) {std::cout << "[exception caught]\n";} }int main () {std::thread threads[10];// spawn 10 threads:for (int i=0; i<10; ++i)threads[i] = std::thread(print_thread_id,i+1);for (auto& th : threads) th.join();return 0; }參考鏈接
- lock_guard
總結(jié)
以上是生活随笔為你收集整理的C++中lock_guard的学习的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Matlab scatter 如何显示不
- 下一篇: C语言 多重指针--整型字符字符串 in