Did not get expected result in Go playground

Issue

I have a very simple go code like this:

var wg sync.WaitGroup
func main() {
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func(i int) {
            fmt.Printf("No %d goroutine begin\n", i)
            fmt.Printf("No %d goroutine is done\n", i)
            wg.Done()
        }(i)
    }
    wg.Wait()
}

On my local computer, with 12 core CPU, this code will output randomly like expected.
But when I run the code in the go playground environment, I get an unexpected result. I know the Go playground only uses one core to run the code, so the expected output should be one by one from No 0 goroutine begin, but it always starts with the last number No 9 goroutine begin. Is that correct or did am I missing something?

Solution

The Go playground has a modified scheduler and other special features.

The Go Blog: Inside the Go Playground

The Go Playground: About

Answered By – peterSO

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.