GMP模型协程调度的练习
package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
runtime.GOMAXPROCS(1)
var sync sync.WaitGroup
sync.Add(6)
go func() {
defer sync.Done()
fmt.Println("goroutine 1")
go func() {
defer sync.Done()
fmt.Println("goroutine 1-1")
go func() {
defer sync.Done()
fmt.Println("goroutine 1-1-1")
}()
}()
go func() {
defer sync.Done()
fmt.Println("goroutine 1-2")
go func() {
defer sync.Done()
fmt.Println("goroutine 1-2-1")
}()
}()
}()
go func() {
defer sync.Done()
fmt.Println("goroutine 2")
}()
sync.Wait()
return
}
- 根据GMP模型,runtime.GOMAXPROCS(1),P只有一个,也就是只能有一个goroutine运行
- P的结构中下一个执行的协程runnext和本地队列runq(先进先出)
故结果为:
goroutine 2
goroutine 1
goroutine 1-2
goroutine 1-2-1
goroutine 1-1
goroutine 1-1-1
本作品采用《CC 协议》,转载必须注明作者和本文链接
我想问下就是为啥 2先出,不是1先出