D
D
Dmitry2022-01-14 20:40:04
go
Dmitry, 2022-01-14 20:40:04

Mutex when reading from a map?

I'm writing a simple session store...

import "sync"

type Session struct {...}

type SessionStorage struct {                                             
    sync.Mutex
    sessions map[string]Session
    ...
}

func (s *SessionStorage) Get(id string) (Session, bool) {
    s.Lock()
    v, ok := s.sessions[id]
    s.Unlock()
    return v, ok
}

func (s *SessionStorage) Set(id string, session Session) {
    s.Lock()
    s.sessions[id] = session
    s.Unlock()
}
...


I have a question. Do I need to synchronize the read from the map ( method Get(...)), or is it an atomic operation in Go?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2022-01-14
@R3cive

You need RWMutex https://pkg.go.dev/sync#RWMutex Read only, no write at all, not guaranteed by spec, but thread safe in current implementation. If write is expected, you also need RWMutex.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question