【发布时间】: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