学习 goroutine 的时候看过这个例子,不太明白为什么会这样?请看代码:
```
// This sample program demonstrates how to create goroutines and
// how the scheduler behaves.
package main
import (
"fmt"
"runtime"
"sync"
)
// main is the entry point for all Go programs.
func main() {
// Allocate 1 logical processor for the scheduler to use.
runtime.GOMAXPROCS(1)
// wg is used to wait for the program to finish.
// Add a count of two, one for each goroutine.
var wg sync.WaitGroup
wg.Add(2)
fmt.Println("Start Goroutines")
// Declare an anonymous function and create a goroutine.
go func() {
// Schedule the call to Done to tell main we are done.
defer wg.Done()
// Display the alphabet three times
for count := 0; count < 3; count++ {
for char := 'a'; char < 'a'+26; char++ {
fmt.Printf("%c ", char)
}
}
}()
// Declare an anonymous function and create a goroutine.
go func() {
// Schedule the call to Done to tell main we are done.
defer wg.Done()
// Display the alphabet three times
for count := 0; count < 3; count++ {
for char := 'A'; char < 'A'+26; char++ {
fmt.Printf("%c ", char)
}
}
}()
// Wait for the goroutines to finish.
fmt.Println("Waiting To Finish")
wg.Wait()
fmt.Println("\nTerminating Program")
}
```
这段代码为什么始终先输出第二个 goroutine 的内容,即大写字母,再输出第一个 goroutine 的内容小写字母?
goroutine 不是无序的吗,为什么这个例子总是顺序一一,并且第二个 goroutine 先打印?
有疑问加站长微信联系(非本文作者)