2
我想知道我應該在該示例中放置互斥鎖?還是應該兩個結構都有一個互斥體?我應該在嵌套結構上還是僅在父窗口上使用sync.Mutex?
我有setter/getters操縱一個*設備,我有一個功能,添加設備到我的狀態結構。
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並從中讀取。 – jonaz 2014-10-06 14:58:37
@DewyBroto是的,在一個路由中讀取並寫入另一個。例如通過Power和SetPower功能。 – jonaz 2014-10-06 15:02:06