How can one implement a thread-safe wrapper to maps in Go by locking?

隐身守侯 提交于 2019-12-06 10:43:31

Effective Go

Pointers vs. Values

The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers. This is because pointer methods can modify the receiver; invoking them on a copy of the value would cause those modifications to be discarded.

To visibly modify the MemStore struct variable mutex field, use a pointer receiver. You are modifying a copy, which is invisible to other go routines. For example,

File keyval.go:

package keyval

import "sync"

type MemStore struct {
    data  map[interface{}]interface{}
    mutex sync.RWMutex
}

func NewMemStore() *MemStore {
    m := &MemStore{
        data: make(map[interface{}]interface{}),
        // mutex does not need initializing
    }
    return m
}

func (m *MemStore) Set(key interface{}, value interface{}) (err error) {
    m.mutex.Lock()
    defer m.mutex.Unlock()

    if value != nil {
        m.data[key] = value
    } else {
        delete(m.data, key)
    }

    return nil
}

File keyval_test.go:

package keyval

import "testing"

func setN(store *MemStore, N int, done chan<- struct{}) {
    for i := 0; i < N; i++ {
        store.Set(i, -i)
    }
    done <- struct{}{}
}

func BenchmarkMemStore(b *testing.B) {
    store := NewMemStore()
    done := make(chan struct{})
    b.ResetTimer()
    go setN(store, b.N, done)
    go setN(store, b.N, done)
    <-done
    <-done
}

Benchmark:

$ go test -v -bench=.
testing: warning: no tests to run
PASS
BenchmarkMemStore    1000000          1244 ns/op
ok      so/test 1.275s
$
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!