共享锁和排它锁---C++17 多线程
生活随笔
收集整理的這篇文章主要介紹了
共享锁和排它锁---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 多线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【JavaScript】appendCh
- 下一篇: s3c2440移植MQTT