I am trying to familiarize with go routines. I have written the following simple program to store the squares of numbers from 1-10 in a map.
func main() {
squares := make(map[int]int)
var wg sync.WaitGroup
for i := 1; i <= 10; i++ {
go func(n int, s map[int]int) {
s[n] = n * n
}(i, squares)
}
wg.Wait()
fmt.Println("Squares::: ", squares)
}
At the end, it prints an empty map. But in go, maps are passed by references. Why is it printing an empty map?
As pointed out in the comments, you need to synchronize access to the map and your usage of sync.WaitGroup
is incorrect.
Try this instead:
func main() {
squares := make(map[int]int)
var lock sync.Mutex
var wg sync.WaitGroup
for i := 1; i <= 10; i++ {
wg.Add(1) // Increment the wait group count
go func(n int, s map[int]int) {
lock.Lock() // Lock the map
s[n] = n * n
lock.Unlock()
wg.Done() // Decrement the wait group count
}(i, squares)
}
wg.Wait()
fmt.Println("Squares::: ", squares)
}