C ++两个锁比一个锁好
c++ two locks better than one?
我有一个资源(向量,列表等),我正在尝试为多个编写器/读者提供访问权限。
我不确定如何做到这一点以获得最佳性能,即,如果数据结构被锁定,则读取器的锁定量最小。使用两个锁会更好吗,一个称为readmutex,另一个称为writemutex?
所以例如:
struct Foo {
mutex writemutex_;
mutex readmutex_;
vector<string> data_;
void write(string data)
{
lock_guard<mutex> locker(writemutex_);
data_.emplace_back(move(data));
}
string get(int index) const {
// I don't need to lock for read, but what if the data is being written?
// and so should I lock lockmutex_? If so, then readmutex_ is unnecessary?
// is there some cleaver way that I can avoid readers from being blocked?
return data_[index];
}
};
我可以在此处使用哪些其他同步技术?
你需要读取器-写入器锁定。但是您应该考虑到,在某些场景中,rw锁可能比独占锁慢
有很多实现,例如在 boost 中。WinAPI也有一个(自Vista或Server 2008以来)
您可以使用
boost中可用的shared_mutex
,并且将成为C++14的一部分。
struct Foo
{
using mutex = boost::shared_mutex;
using write_lock = boost::unique_lock<mutex>;
using read_lock = boost::shared_lock<mutex>;
mutable mutex mutex_;
vector<string> data_;
void write(string data)
{
write_lock lock{ mutex_ };
data_.emplace_back(move(data));
}
string get(int index) const
{
read_lock lock{ mutex_ };
return data_[index];
}
};
回答您的主要问题:不,使用两个锁并不好。这实际上是不正确的。您需要写锁定来防止竞争,并且在持有写锁定时,不需要任何额外的读锁定。
其他答案确实有正确的替代方案(shared_mutex,它实现了读写锁),但没有解释为什么需要它。
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 使用一个循环与两个循环
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 在Qt/C++中从一个代码构建两个略有不同的项目
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 如果两个静态库使用相同的另一个静态库,如何避免"LNK2005 Already Defined error"?
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- 将两个 cpp 文件合并为一个 cpp 文件
- 为什么将两个浮点数相加会得到一个整数C++?
- 我如何创建一个列表,然后从中创建两个列表,其中一个用于偶数,另一个用于奇数?
- 如何得到一个两个数字都相等或这个数字更大