我有一个对象,它unordered_map
使用字符串键和变量值存储一些设置。由于我的库可能会被多个线程使用,并且读取的数量很可能会大大超过写入的数量,因此我考虑过一个写入时复制实现,其中“get”操作是无锁的,而“put”操作是关键的部分,如示例中所示:
class Cfg {
using M = unordered_map<string,X>;
shared_ptr<const M> data;
mutex write_lock;
public:
X get(string key) {
shared_ptr<const M> cur_ver = atomic_load_explicit(&data, memory_order_acquire);
// Extract the value from the immutable *cur_ver
}
void put(string key, X value) {
lock<muted> wlock(write_lock);
// No need for the atomic load here because of the lock
shared_ptr<const M> cur_ver = data;
shared_ptr<const M> new_ver = ;// create new map with value included
// QUESTION: do I need this store to be atomic? Is it even enough?
atomic_store_explicit(&data, new_ver, memory_order_release);
}
}
只要获取/释放同步也会影响指向的数据而不仅仅是指针值,我有理由相信该设计是有效的。但是,我的问题如下:
- 这个工作需要锁内的原子存储吗?
- 或者原子获取是否会与作为“释放”操作的互斥锁同步?