algorithm - 并发重读工作负载的数据结构

标签 algorithm go data-structures containers

我正在寻找一种存储 32 字节字符串并允许使用首选 O(1) 或 O(log N) 查找复杂度进行快速查找的数据结构(目标只是确定键是否存在)。删除和插入的复杂性并不重要,因为这些操作很少见。

这与问题无关,但我在 Go 中工作。我可以使用由互斥体支持的 hashmap,但争用会是个问题,如果有更好的解决方案,我宁愿避免分片。

谢谢

最佳答案

map 对于并发读取是安全的。您可以将所需的 map 放入 sync/atomic.Value 中,当您想要写入它时,复制 map 并更改它,然后将其放回 Value 中。来自 docs :

The following example shows how to maintain a scalable frequently read, but infrequently updated data structure using copy-on-write idiom.

Code:

type Map map[string]string
var m Value
m.Store(make(Map))
var mu sync.Mutex // used only by writers
// read function can be used to read the data without further synchronization
read := func(key string) (val string) {
        m1 := m.Load().(Map)
        return m1[key]
}
// insert function can be used to update the data without further synchronization
insert := func(key, val string) {
        mu.Lock() // synchronize with other potential writers
        defer mu.Unlock()
        m1 := m.Load().(Map) // load current value of the data structure
        m2 := make(Map)      // create a new value
        for k, v := range m1 {
                m2[k] = v // copy all data from the current object to the new one
        }
        m2[key] = val // do the update that we need
        m.Store(m2)   // atomically replace the current object with the new one
        // At this point all new readers start working with the new version.
        // The old version will be garbage collected once the existing readers
        // (if any) are done with it.
}
_, _ = read, insert

您还可以使用指向您的指针 map 而不是 Value 并使用 StorePointer/LoadPointer 自动存储它但这并不干净,因为您应该使用不安全的指针并强制转换它。

关于algorithm - 并发重读工作负载的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48039010/

相关文章:

为设置的表格宽度计算可变列宽的算法

algorithm - 改进 Box Factory 解决方案

go - 使用 golang 模板在 div 中填充许多 Html 元素?

multithreading - goroutine 或多线程在 golang 中不起作用

python - 如何在导致python脚本错误的大数据上查找特定行?

c++ - 如何使用递归反转链表?

algorithm - 描述一个递归算法打印所有没有任何连续 1 的 N 位二进制字符串

arrays - 在 for-in 循环中更改数组的大小

email - 戈兰 : How to UTF8 both subject header and body in email?

algorithm - AVL 树 : How to do index access?