dongxuying7583 2016-08-10 13:49
浏览 36
已采纳

golang调度程序如何在以下代码中调度goroutine?

package main

import (
    "fmt"
    "time"
    "runtime"
)

var quit chan int = make(chan int)

func loop(a int) {
    fmt.Println(a)
    for i := 0; i < 30000000000; i++ {
    }
    fmt.Println(a)
    quit <- 0
}

func main() {
    runtime.GOMAXPROCS(1)

    go loop(1)
    time.Sleep(time.Second)
    go loop(2)

    for i := 0; i < 2; i++ {
        <-quit
    }
}

For the scheduler model (M+P+G), I suppose we just have 1 cpu context because we set GOMAXPROCS as 1, and there is just 1 thread(M) here.

In the goroutine, the for loop do not has any IO blocking, so no new thread will be generated, all goroutine should still work in current thread, so I think the 2 goroutine must go one by one, thus, the result should be 1 1 2 2. But in fact, the result is 1 2 1 2. Why?

  • 写回答

1条回答 默认 最新

  • dounao4179 2016-08-10 14:55
    关注

    Here's the order of the relevant operations in your program.

    1. go loop(1) dispatches goroutine loop1
    2. time.Sleep(time.Second) starts in the main goroutine
    3. fmt.Println(a) called from loop1, prints 1
    4. loop1 enters busy loop and holds the CPU
    5. entry to fmt.Println(a) from loop1 yields to the scheduler
    6. main goroutine wakes up, finishes the time.Sleep call
    7. go loop(2) dispatches goroutine loop2
    8. fmt.Println(a) called from loop2, prints 2
    9. loop2 enters busy loop and holds the CPU
    10. entry to fmt.Println(a) from loop2 yields to the scheduler
    11. loop1 one wakes up and finishes fmt.Println(a), prints 1
    12. loop1 sends 0 over the quit channel
    13. loop2 finishes fmt.Println(a), prints 2
    14. loop2 sends 0 over the quit channel
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证