2014-10-06 85 views
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 
} 
+0

State變量是全局變量,它將同時寫入不同的goroutine並從中讀取。 – jonaz 2014-10-06 14:58:37

+0

@DewyBroto是的,在一個路由中讀取並寫入另一個。例如通過Power和SetPower功能。 – jonaz 2014-10-06 15:02:06

回答

4

其實你應該有2個不同的互斥(是複數?),一個以保護該設備的地圖訪問和一個。

啓動幾個Go例程在地圖和設備上執行任務,並使用​​或go build -race和99%的時間運行程序,它會向您顯示需要使用鎖的確切位置。

我建議通過Race Detector文件。

+0

downvote的任何原因? – OneOfOne 2014-10-06 08:53:16

相關問題