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

huangapple go评论80阅读模式
英文:

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

问题

我正在为你翻译以下内容:

我想知道在这个例子中应该把互斥锁放在哪里?或者两个结构体都应该有一个互斥锁?

我有用于操作 *Device 的设置器/获取器,并且我有一个用于将设备添加到我的 State 结构体的函数。

type State struct {
    Devices map[string]*Device
    // 这里应该放互斥锁吗?
}

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 {
    // 或者这里应该放互斥锁吗?
    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
}

希望对你有帮助!

英文:

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
}

答案1

得分: 4

实际上,你应该有两个不同的互斥锁(这是复数吗?),一个用于保护地图访问,另一个用于设备。

启动几个Go协程来处理地图和设备,并使用go run -race *.gogo build -race运行程序,99%的情况下它会准确地显示你需要使用锁的位置。

我建议你阅读竞态检测器(Race Detector)文档。

英文:

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.

huangapple
  • 本文由 发表于 2014年10月6日 15:54:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/26211963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定