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

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

读写锁把对共享资源的访问者划分成读者和写者,读者只对共享资源进行读访问,写者则需要对共享资源进行写操作。C++17开始,标准库提供了shared_mutex类(在这之前,可以使用boostshared_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版)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值