映射并发访问

问题描述 投票:57回答:7

在具有并发访问权限的程序中使用映射时,是否需要在函数中使用互斥锁来读取值?

map go mutex
7个回答
89
投票

多个读者,没有作家是好的:

https://groups.google.com/d/msg/golang-nuts/HpLWnGTp-n8/hyUYmnWJqiQJ

一位作家,没有读者可以。 (否则地图不会太好。)

否则,如果至少有一个编写器和至少一个编写器或读者,则所有读者和编写者必须使用同步来访问该映射。互斥锁可以正常工作。


43
投票

2017年4月27日,sync.Map已与Go大师合并。

这是我们一直在等待的并发Map。

https://github.com/golang/go/blob/master/src/sync/map.go

https://godoc.org/sync#Map


21
投票

几天前我在this reddit thread中回答了你的问题:

在Go中,映射不是线程安全的。此外,例如,如果可能存在写入相同数据的另一个goroutine(同时,即),则数据甚至需要锁定。

从你在评论中的澄清来看,也会有定制函数,你问题的答案是肯定的,你必须用互斥体来保护你的读物;你可以使用RWMutex。举个例子,你可以看一下我编写的表数据结构(使用幕后地图)的实现的source(实际上是在reddit线程中链接的那个)。


17
投票

您可以使用concurrent-map来处理并发性问题。

// Create a new map.
map := cmap.NewConcurrentMap()

// Add item to map, adds "bar" under key "foo"
map.Add("foo", "bar")

// Retrieve item from map.
tmp, ok := map.Get("foo")

// Checks if item exists
if ok == true {
    // Map stores items as interface{}, hence we'll have to cast.
    bar := tmp.(string)
}

// Removes item under key "foo"
map.Remove("foo")

2
投票

如果你只有一个作家,那么你可能会使用原子价值。以下内容改编自https://golang.org/pkg/sync/atomic/#example_Value_readMostly(原版使用锁来保护书写,因此支持多个作者)

type Map map[string]string
    var m Value
    m.Store(make(Map))

read := func(key string) (val string) { // read from multiple go routines
            m1 := m.Load().(Map)
            return m1[key]
    }

insert := func(key, val string) {  // update from one go routine
            m1 := m.Load().(Map) // load current value of the data structure
            m2 := make(Map)      // create a new map
            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 (can delete/add/change)
            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.
    }

0
投票

为什么没有使用Go并发模型代替,有一个简单的例子......

type DataManager struct {
    /** This contain connection to know dataStore **/
    m_dataStores map[string]DataStore

    /** That channel is use to access the dataStores map **/
    m_dataStoreChan chan map[string]interface{}
}

func newDataManager() *DataManager {
    dataManager := new(DataManager)
    dataManager.m_dataStores = make(map[string]DataStore)
    dataManager.m_dataStoreChan = make(chan map[string]interface{}, 0)
    // Concurrency...
    go func() {
        for {
            select {
            case op := <-dataManager.m_dataStoreChan:
                if op["op"] == "getDataStore" {
                    storeId := op["storeId"].(string)
                    op["store"].(chan DataStore) <- dataManager.m_dataStores[storeId]
                } else if op["op"] == "getDataStores" {
                    stores := make([]DataStore, 0)
                    for _, store := range dataManager.m_dataStores {
                        stores = append(stores, store)
                    }
                    op["stores"].(chan []DataStore) <- stores
                } else if op["op"] == "setDataStore" {
                    store := op["store"].(DataStore)
                    dataManager.m_dataStores[store.GetId()] = store
                } else if op["op"] == "removeDataStore" {
                    storeId := op["storeId"].(string)
                    delete(dataManager.m_dataStores, storeId)
                }
            }
        }
    }()

    return dataManager
}

/**
 * Access Map functions...
 */
func (this *DataManager) getDataStore(id string) DataStore {
    arguments := make(map[string]interface{})
    arguments["op"] = "getDataStore"
    arguments["storeId"] = id
    result := make(chan DataStore)
    arguments["store"] = result
    this.m_dataStoreChan <- arguments
    return <-result
}

func (this *DataManager) getDataStores() []DataStore {
    arguments := make(map[string]interface{})
    arguments["op"] = "getDataStores"
    result := make(chan []DataStore)
    arguments["stores"] = result
    this.m_dataStoreChan <- arguments
    return <-result
}

func (this *DataManager) setDataStore(store DataStore) {
    arguments := make(map[string]interface{})
    arguments["op"] = "setDataStore"
    arguments["store"] = store
    this.m_dataStoreChan <- arguments
}

func (this *DataManager) removeDataStore(id string) {
    arguments := make(map[string]interface{})
    arguments["storeId"] = id
    arguments["op"] = "removeDataStore"
    this.m_dataStoreChan <- arguments
}

0
投票

我的简单实现:

import (
    "sync"
)

type AtomicMap struct {
    data   map[string]string
    rwLock sync.RWMutex
}

func (self *AtomicMap) Get(key string) (string, bool) {
    self.rwLock.RLock()
    defer self.rwLock.RUnlock()
    val, found := self.data[key]
    return val, found
}

func (self *AtomicMap) Set(key, val string) {
    self.rwLock.Lock()
    defer self.rwLock.Unlock()
    self.data[key] = val
}
© www.soinside.com 2019 - 2024. All rights reserved.