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

歡迎訪問 生活随笔!

生活随笔

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

c/c++

共享锁和排它锁---C++17 多线程

發布時間:2023/12/10 c/c++ 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 共享锁和排它锁---C++17 多线程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

共享鎖和排它鎖—C++17 多線程

讀寫鎖把對共享資源的訪問者劃分成讀者和寫者,讀者只對共享資源進行讀訪問,寫者則需要對共享資源進行寫操作。C++17開始,標準庫提供了shared_mutex類(在這之前,可以使用boost的shared_mutex類或系統相關api)。和其他便于獨占訪問的互斥類型不同,shared_mutex 擁有兩個訪問級別:

  • 共享:多個線程能共享同一互斥的所有權(如配合shared_lock);
  • 獨占:僅有一個線程能占有互斥(如配合lock_guard、unique_lock)。

shared_mutex適用于多線程同時讀取是不發生競爭,寫入時發出競爭

#include <iostream> #include <thread> #include <map> #include <mutex> #include <shared_mutex>using namespace std;class DnsEntry { private:std::string ip; public:DnsEntry(){}DnsEntry(std::string _ip): ip(_ip){} };class DnsCatch { private:std::map<std::string, DnsEntry> entries;mutable std::shared_mutex entry_mutex; public:// 多個線程可以同時調用DnsEntry find_entry(std::string const& domain) const{std::shared_lock<std::shared_mutex> lk(entry_mutex);std::cout << "讀取\n";std::map<std::string, DnsEntry>::const_iterator const it = entries.find(domain);return (it == entries.end()) ? DnsEntry() : it->second;}// 只有一個線程可以調用void update_or_add_entry(std::string const& domain, DnsEntry const& dns_details){std::unique_lock<std::shared_mutex> lk(entry_mutex);std::cout << "更新\n";entries[domain] = dns_details;} };

參考《C++并發編程實戰(第2版)

總結

以上是生活随笔為你收集整理的共享锁和排它锁---C++17 多线程的全部內容,希望文章能夠幫你解決所遇到的問題。

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