

深入理解 Go | 调度:GMP 模型(第二部分)
source link: https://ictar.github.io/2020/04/14/dive-into-go-schedule-gpm-part2/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

深入理解 Go | 调度:GMP 模型(第二部分)
启动调度器
Go 程序启动之后,在进入 main()
之前,会调用 runtime.schedinit()
启动调度器:
调度器启动后,Go 运行时就会调用 runtime.mstart()
初始化一个新线程,然后调用 runtime.schedule()
进入调度循环(永不返回)。调度循环会查找一个可运行的 goroutine,然后在当前线程上执行这个 goroutine。
可运行 goroutine 的来源有: * 全局可运行队列 * 与处理器 P 绑定的本地可运行队列 * netpoll * 从其他处理器 P 的本地可运行队列中窃取
创建 goroutine
在编译阶段,go fn()
会转换成运行时调用 runtime.newproc()
。这个函数在从(本地/全局)空闲 goroutine 列表从获取不到一个可用的 goroutine 才会新建一个。并且,会将 fn 调用的参数和 runtime.goexit()
的 PC 保存在 goroutine 的栈中。
goroutine 执行完毕
在调度 goroutine 运行的时候,runtime.goexit()
位于调用栈的顶端,因此,当 goroutine 对应的函数运行完毕后,就会跳转执行 runtime.goexit()
:
Recommend
-
19
Golang最大的特色可以说是协程(goroutine)了, 协程让本来很复杂的异步编程变得简单, 让程序员不再需要面对回调地狱, 虽然现在引入了协程的语言越来越多, 但go中的协程仍然是实现的是最彻底的. 这篇文章将通过分析golang...
-
11
Golang 调度器四个重要结构 :M P G Sched GMP的结构源码在文件中\src\runtime\runtime2.go 简介 G :goroutine,go程序建立的用户线程。主要保存 goroutine 的运行时栈信息(stack结构体...
-
9
[典藏版] Golang 调度器 GMP 原理与调度全分析 / 2025 / 35 / 发布于 2年前 /
-
3
GMP调度模型 发表于 2021-07-09 更新于 2021-09-20 分类于 Golang , 基础 阅读次数: 28...
-
6
深入理解 Go | 调度:GMP 模型(第一部分) 发表于 2020-04-13...
-
7
深入理解 Go | 调度:GMP 模型(第三部分) 发表于 2020-04-14...
-
6
Statement This article is my study notes about distributed systems. Please refer to the original work for more details and indicate the source for reprinting. 1. Goroutine Goroutine = Golang...
-
5
GMP调度 runtime调度器的三个重要组成部分:线程M、Goroutine G和处理器P: G-Goroutine协程,在运行时调度器中跟线程在操作系统差不多,但是用了更小的内存空间。 M-操作系统的线程,由操作系统调度器调度管理。 P-表...
-
6
【2-1 Golang】Go并发编程—GMP调度模型概述 tomato01 · 4分钟之前 · 75...
-
7
Golang篇-深入理解GMP调度模型 - 麦奇 麦奇
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK