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
}
  1. 根据GMP模型,runtime.GOMAXPROCS(1),P只有一个,也就是只能有一个goroutine运行
  2. P的结构中下一个执行的协程runnext和本地队列runq(先进先出)

故结果为:

goroutine 2
goroutine 1
goroutine 1-2
goroutine 1-2-1
goroutine 1-1
goroutine 1-1-1
本作品采用《CC 协议》,转载必须注明作者和本文链接
野生菌
讨论数量: 4

我想问下就是为啥 2先出,不是1先出

1年前 评论
野生菌 (楼主) 1年前
中文 (作者) 1年前
野生菌 (楼主) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!