I have this simplistic piece of code (or here https://play.golang.org/p/KW8_OHUp9v)
package main
import (
"fmt"
"sync"
)
func main() {
mutex := new(sync.Mutex)
for i := 1; i < 5; i++ {
for j := 1; j < 5; j++ {
mutex.Lock()
go func() {
fmt.Printf("%d + %d = %d
", i, j, j+i)
mutex.Unlock()
}()
}
}
}
It produces an output like this
1 + 2 = 3
1 + 3 = 4
1 + 4 = 5
2 + 5 = 7
2 + 2 = 4
2 + 3 = 5
2 + 4 = 6
3 + 5 = 8
3 + 2 = 5
3 + 3 = 6
3 + 4 = 7
4 + 5 = 9
4 + 2 = 6
4 + 3 = 7
4 + 4 = 8
Program exited.
Looking at the output I was surprised by few things:
- There are no '1's for the
j
- There are '5's for the
j
- There are only 3 values for i=1, instead of 4
I can understand lack of '1's as the variable is incremented before it is written.
Can someone explain 2. and 3. ?