go - Goroutines sharing an array channel : trying to solve data race -


i try write complex program parallel goroutines. first program channels ;) each goroutine returns array and, unfortunately, result "random". if run 10 times program, have 10 different results :(

this on simplification of program, results (maybe because simple) when run -race argument, there 4 data races.

i tried had close() function did not worked.

may me find mistake ? thank in advance !

package main  import "fmt" import "sync" import "strconv"   func cat_strings(a int, b string) []string{     var y []string      j := strconv.itoa(a)     y = append(y, j)     y = append(y, b)     return y }  func main() {     var slice []string     var wg sync.waitgroup     var x []string      queue := make(chan []string, 10)      wg.add(10)     := 0; < 10; i++ {         go func(i int) {             defer wg.done()             x = cat_strings(i, "var")             queue <- x         }(i)      }     //close(queue)      go func() {         defer wg.done()         t := range queue {             slice = append(slice, t...)         }     }()      wg.wait()     fmt.println(slice) } 

there's 2 pieces fix, don't share slices between goroutines, , range on queue synchronously in main.

import (     "fmt"     "strconv"     "sync" )  func cat_strings(a int, b string) []string {     var y []string      j := strconv.itoa(a)     y = append(y, j)     y = append(y, b)     return y }  func main() {     var slice []string     var wg sync.waitgroup      queue := make(chan []string, 10)      wg.add(10)     := 0; < 10; i++ {         go func(i int) {             defer wg.done()             queue <- cat_strings(i, "var")         }(i)      }      go func() {         wg.wait()         close(queue)     }()      t := range queue {         slice = append(slice, t...)     }      fmt.println(slice) } 

there's no reason x slice you're sharing between goroutines. if each goroutine needs slice, define new 1 each. sharing single slice going require synchronization.

the other race between goruoutine appending queue slice slice, , final fmt.println. there's no reason concurrent since don't want print until values have been read, finish for-range loop entirely before printing final value.


Comments