go - Golang concurrency: how to append to the same slice from different goroutines -
i have concurrent goroutines want append (pointer a) struct same slice. how write in go make concurrency-safe?
this concurrency-unsafe code, using wait group:
var wg sync.waitgroup myslice = make([]*mystruct) _, param := range params { wg.add(1) go func(param string) { defer wg.done() oneofmystructs := getmystruct(param) myslice = append(myslice, &oneofmystructs) }(param) } wg.wait()
i guess need use go channels concurrency-safety. can contribute example?
there nothing wrong guarding myslice = append(myslice, &oneofmystructs)
sync.mutex. of course can have result channel buffer size len(params)
goroutines send answers , once work finished collect result channel.
if params
has fixed size:
myslice = make([]*mystruct, len(params)) i, param := range params { wg.add(1) go func(i int, param string) { defer wg.done() oneofmystructs := getmystruct(param) myslice[i] = &oneofmystructs }(i, param) }
as goroutines write different memory isn't racy.
Comments
Post a Comment