【发布时间】:2023-12-27 00:22:02
【问题描述】:
我有一个对象,它在 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);
}
}
只要获取/释放同步也会影响指向的数据而不仅仅是指针值,我有理由相信该设计有效。但是,我的问题如下:
- 此操作是否需要锁内的原子存储?
- 或者原子获取是否会与互斥解锁同步,这是一个“释放”操作?
【问题讨论】:
标签: c++ synchronization mutex atomic happens-before