日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++中lock_guard的学习

發布時間:2023/12/13 c/c++ 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++中lock_guard的学习 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

lock_guard

  • 鎖守衛是一個管理mutex對象的對象,使其始終處于鎖定狀態。
  • 在構造時,mutex對象被調用線程鎖定,在銷毀時,mutex被解鎖。這是最簡單的鎖,作為一個自動持續時間的對象,它的作用特別大,可以持續到上下文結束。通過這種方式,它可以保證mutex對象在發生異常時被正確解鎖。
  • 但請注意,lock_guard對象并不以任何方式管理mutex對象的壽命:mutex對象的持續時間至少應延長到鎖定它的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

總結

以上是生活随笔為你收集整理的C++中lock_guard的学习的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。