jonaz
jonaz

Reputation: 4134

Should I use sync.Mutex on nested structs or only on the parent?

I'm wondering where I should put the mutex in the example? Or should both structs have a mutex?

I have setters/getters for manipulating a *Device and I have a function for adding Devices to my State struct.

type State struct {
    Devices map[string]*Device
    //Should the sync.Mutex be here?
}

func (s *State) AddDevice(id [4]byte, name string, features []string, state string) {
    d := NewDevice(id, name, state, "", features)

    s.Devices[d.Id()] = d
}

func NewState() *State {
    return &State{make(map[string]*Device)}
}
type Device struct {
    //Or Should the sync.Mutex be here?
    SenderId  string
    Name      string
    State     string
    Type      string
    Features  []string
    EEPs      []string
    Power     int64
    PowerUnit string
}

func (d *Device) Power() int64 {
    return d.Power
}
func (d *Device) SetPower(p int64) {
    d.Power = p
}

func NewDevice(id [4]byte, name, state, dtype string, features []string) *Device {
    d := &Device{Name: name, State: state, Type: dtype}
    d.SetId(id)
    return d
}

Upvotes: 2

Views: 1256

Answers (1)

OneOfOne
OneOfOne

Reputation: 99351

Actually you should have 2 different Mutexes (is that the plural?), one to protect the map access and one for the device.

Start few Go routines to do things on both the map and devices and run the program with go run -race *.go or go build -race and 99% of the time it will show you exactly where you need to use locks.

I recommend going through the Race Detector document.

Upvotes: 4

Related Questions