Tuesday, 27 August 2013

Working with slices of structs concurrently using references

Working with slices of structs concurrently using references

I have a JSON I need to do some processing on. It uses a slice that I need
to reference in some way for the Room-struct to be modified at the end of
the function. How can I work with this struct concurrently in a by
reference type of way?
http://play.golang.org/p/wRhd1sDqtb
type Window struct {
Height int64 `json:"Height"`
Width int64 `json:"Width"`
}
type Room struct {
Windows []Window `json:"Windows"`
}
func main() {
js :=
[]byte(`{"Windows":[{"Height":10,"Width":20},{"Height":10,"Width":20}]}`)
fmt.Printf("Should have 2 windows: %v\n", string(js))
var room Room
_ = json.Unmarshal(js, &room)
var wg sync.WaitGroup
// Add meny windows to room
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
addWindow(room.Windows)
}()
}
wg.Wait()
js, _ = json.Marshal(room)
fmt.Printf("Sould have 12 windows: %v\n", string(js))
}
func addWindow(windows []Window) {
window := Window{1, 1}
fmt.Printf("Adding %v to %v\n", window, windows)
windows = append(windows, window)
}

No comments:

Post a Comment