I have concurrent goroutines which want to append a (pointer to a) struct to the same slice.
How do you write that in Go to make it concurrency-safe?
This would be my concurrency-unsafe code, using a wait group:
var wg sync.WaitGroup
MySlice = make([]*MyStruct)
for _, 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 you would need to use go channels for concurrency-safety. Can anyone contribute with an example?
question from:
https://stackoverflow.com/questions/18499352/golang-concurrency-how-to-append-to-the-same-slice-from-different-goroutines 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…