登录
首页 >  Golang >  Go问答

解决Golang Map 并发访问问题的方法

来源:stackoverflow

时间:2024-03-28 13:18:30 408浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《解决Golang Map 并发访问问题的方法》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

现在我有一个只有一个写/删除goroutine和许多读goroutine的Map,有一些并发访问的Map解决方案,例如RWMutex,sync.map,concurrent-map,sync.atomic,sync.Value,对我来说最好的选择是什么?

RWMutex的读锁有点多余

sync.map 和并发映射专注于许多写入 goroutine


解决方案


你的问题有点模糊 - 所以我会分解它。

选择取决于您对地图的性能要求。我会选择基于简单互斥体(或 rwmutex)的方法。

当然,您可以从 concurrent map 获得更好的性能。sync.mutex 锁定所有地图存储桶,而在并发地图中,每个存储桶都有自己的 sync.mutex

再次强调 - 这完全取决于您的程序的规模和您所需的性能。

为了确保正确使用地图,您可以将其包装在 struct 中。

type store struct {
    data              map[t]t
}

这是一个更加面向对象的解决方案,但它允许我们确保任何读/写操作都是并发执行的。除此之外,我们还可以轻松存储可能对调试或安全有用的其他信息,例如作者。

现在,我们将使用一组方法来实现这一点,如下所示:

mux sync.Mutex

// New initialises a Store type with an empty map
func New(t, h uint) *Store {
    return &Store{
        Data:     map[T]T{},
    }
}

// Insert adds a new key i to the store and places the value of x at this location
// If there is an error, this is returned - if not, this is nil
func (s *Store) Insert(i, x T) error {
    mux.Lock()
    defer mux.Unlock()
    _, ok := s.Data[i]
    if ok {
        return fmt.Errorf("index %s already exists; use update", i)
    }
    s.Data[i] = x
    return nil
}

// Update changes the value found at key i to x
// If there is an error, this is returned - if not, this is nil
func (s *Store) Update(i, x T) error {
    mux.Lock()
    defer mux.Unlock()
    _, ok := s.Data[i]
    if !ok {
        return fmt.Errorf("value at index %s does not exist; use insert", i)
    }
    s.Data[i] = x
    return nil
}

// Fetch returns the value found at index i in the store
// If there is an error, this is returned - if not, this is nil
func (s *Store) Fetch(i T) (T, error) {
    mux.Lock()
    defer mux.Unlock()
    v, ok := s.Data[i]
    if !ok {
        return "", fmt.Errorf("no value for key %s exists", i)
    }
    return v, nil
}

// Delete removes the index i from store
// If there is an error, this is returned - if not, this is nil
func (s *Store) Delete(i T) (T, error) {
    mux.Lock()
    defer mux.Unlock()
    v, ok := s.Data[i]
    if !ok {
        return "", fmt.Errorf("index %s already empty", i)
    }
    delete(s.Data, i)
    return v, nil
}

在我的解决方案中,我使用了一个简单的 sync.mutex - 但您可以简单地更改此代码以适应 rwmutex。

我建议您查看How to use RWMutex in Golang?

终于介绍完啦!小伙伴们,这篇关于《解决Golang Map 并发访问问题的方法》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>