dongxiezhi9564 2014-10-06 07:54
浏览 40
已采纳

我应该在嵌套结构上还是仅在父结构上使用sync.Mutex?

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条回答 默认 最新

  • douzhang1364 2014-10-06 08:09
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题