"how can one implement a thread-safe wrapper to maps in go by locking?" Code Answer


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) {
    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{})
    go setn(store, b.n, done)
    go setn(store, b.n, done)


$ go test -v -bench=.
testing: warning: no tests to run
benchmarkmemstore    1000000          1244 ns/op
ok      so/test 1.275s
By MrJman006 on September 20 2022

Answers related to “how can one implement a thread-safe wrapper to maps in go by locking?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.