I’m having trouble trying to work out how to update a slice from parallel goroutines. I initially came up with this code (that I knew wasn’t the correct way to do it!):
func main() {
var dwpList = []int {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var mmrpList []int
var wg sync.WaitGroup
ch1 := make(chan int)
cores := 4
wg.Add(cores + 1)
for i := 0; i < cores; i++ {
go func1(&mmrpList, ch1, &wg)
}
iterateSamples(dwpList, ch1, &wg)
close(ch1)
wg.Wait()
fmt.Println(mmrpList)
}
func iterateSamples(dwpList []int, ch1 chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for _, dwp := range dwpList {
ch1 <- dwp
}
}
func func1(mmrpList *[]int, ch1 <-chan int, wg *sync.WaitGroup) {
defer wg.Done()
for dwp := range ch1 {
*mmrpList = append(*mmrpList, dwp)
}
}
Obviously this doesn’t work as there are multiple goroutines appending to the slice at the same time.
The problem is, whenever I try to move the append into it’s own function controlled by extra channels, waitgroups, etc. I always run into compile or ‘deadlock’ issues (which aren’t always deadlocks but a wg Wait or Done issue), or it reverts back to being single-threaded.
Can you please guide me as to how this should be achieved?