I am using waitgroups for the first time. I ran the code but the order in which the code runs is opposite of what I expect.
Expected result:
Hello, playground
Counter: 0
Counter: 1
Kindly help me.
https://play.golang.org/p/U4TDVTbDzN4
I am using waitgroups for the first time. I ran the code but the order in which the code runs is opposite of what I expect.
Expected result:
Hello, playground
Counter: 0
Counter: 1
Kindly help me.
https://play.golang.org/p/U4TDVTbDzN4
Your expectation is wrong. The goroutine scheduler is not deterministic.
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func printer(counter int) {
fmt.Println("Counter:\t", counter)
wg.Done()
}
func main() {
counter := 0
for i := 0; i < 10; i++ {
wg.Add(1)
go printer(counter)
counter++
}
wg.Wait()
}
https://play.golang.org/p/wMs_I-7MRxN.
. Run 1:
Counter: 9
Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
Counter: 7
Counter: 6
Counter: 8
. Run 2:
Counter: 9
Counter: 0
Counter: 1
Counter: 5
Counter: 2
Counter: 3
Counter: 4
Counter: 7
Counter: 6
Counter: 8
. Run 3:
Counter: 9
Counter: 3
Counter: 0
Counter: 1
Counter: 2
Counter: 6
Counter: 4
Counter: 5
Counter: 7
Counter: 8
.
Thanks for the help.
Really appreciate it.