【问题标题】:Should I use sync.Mutex on nested structs or only on the parent?我应该在嵌套结构上使用 sync.Mutex 还是只在父结构上使用?
【发布时间】:2014-10-06 07:54:01
【问题描述】:

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

我有用于操作 *Device 的 setter/getter,并且我有一个用于将 Devices 添加到我的 State 结构的函数。

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
}

【问题讨论】:

  • State 变量是全局变量,将同时在不同的 goroutine 中写入和读取。
  • @DewyBroto 是的,在一个路由中读取并在另一个路由中写入。例如通过 Power 和 SetPower 函数。

标签: go


【解决方案1】:

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

启动几个 Go 例程,在地图和设备上执行操作,并使用 go run -race *.go 或 go build -race 运行程序,并且 99% 的时间它会准确显示您需要在哪里使用锁。

我建议仔细阅读Race Detector 文档。

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    相关资源
    最近更新 更多