当前位置:网站首页>GO语言并发模型-MPG模型
GO语言并发模型-MPG模型
2022-06-24 13:03:00 【一边学习一边哭】

Go语言调度器内部有三个重要的组成部分:M、P、G
- M是Machine,系统线程。它是由操作系统管理的,goroutine就是跑在M之上的。M是一个很大的结构,里面维护小对象内存cache(mcache)、当前执行的goroutine、随机数发生器等非常多信息。
- P是Processor,代表程序执行上下文、处理器。P可以看作是一个局部调度器,P将等待运行的G与M进行对接。它维护了一个goroutine队列,即runqueue。GO的运行时系统会让M和P适时地建里或者断开关联。
- G是goroutine,可以有多个。它包含了栈、指令指针、正在等待地channel,以及其他对调度goroutine的重要信息。
MPG模型

正在执行的goroutine为蓝色,处于待执行的goroutine为灰色。待执行的goroutine都存放于runqueue中,P维护者这个runqueue。每当由新的goroutine被执行,就会加入runqueue。
其实go语言运行时系统在早期并没有P这个概念,go语言的调度器直接把G分配到适当的M上。但是这样做的问题就是G并发运行时需要向系统申请资源,会带来性能损耗。
从go的1.1版本开始,在运行时系统中加入了P,由P来管理G对象,M想要运行G时就需要绑定P。这样带来的好处就是,可以在P对象中预先申请一些系统资源,当G需要的时候先向自己的P去申请。P资源如果也不够了,才会去向全局申请资源,而且会多拿一部分资源以供后面的G去使用。
而且P解耦了M和G的关系。如果有G发生了阻塞,P可以带着其他的G与新的M进行绑定,使得G总是能及时地运行起来,从而提高并发能力。
goroutine发生阻塞

M1可能是新被创建的,也有可能是从缓存中直接拿过来的。
当G0发生阻塞时,P会与当前的M0、G0解绑。M1与P进行绑定,继续执行P下的其他的goroutine。
runqueue执行完成
当由Processor的runqueue执行完成,为空时。他会从其他的Processor上偷取一半的goroutine。

边栏推荐
猜你喜欢
![[leetcode] 10. Regular expression matching](/img/a9/4cdf8d46068a2d7ea6ac212f416157.png)
[leetcode] 10. Regular expression matching

港股上市公司公告 API 数据接口

Unity 热力图建立方法

谷歌WayMo提出R4D: 采用参考目标做远程距离估计

Method of inputting dots under letters in markdown/latex

数商云:加强供应商管理,助推航空运输企业与供应商高效协同

Getting to know cloud native security for the first time: the best guarantee in the cloud Era
![Jerry's serial port receiving IO needs to set the digital function [chapter]](/img/04/48e7da42101a53827463d479952f67.png)
Jerry's serial port receiving IO needs to set the digital function [chapter]

**Puzzling little problem in unity - light and sky box

Idea connection MySQL custom generated entity class code
随机推荐
leetcode 139. Word Break 单词拆分(中等)
【无标题】
**Puzzling little problem in unity - light and sky box
谷歌WayMo提出R4D: 采用参考目标做远程距离估计
Baidu map API drawing points and tips
数据库一些基本操作(提供了原数据库信息)
HarmonyOS.2
SAP Marketing Cloud 功能概述(四)
【LeetCode】10、正则表达式匹配
如何避免下重复订单
2022 Quality Officer - Equipment direction - post skills (Quality Officer) recurrent training question bank and online simulation examination
Jericho may have some chips with fast music playing speed [chapter]
Jericho After sleep, the system will wake up regularly and continue to run without resetting [chapter]
一文搞定 UDP 和 TCP 高频面试题!
P2pdb white paper
根据前序&中序遍历生成二叉树[左子树|根|右子树的划分/生成/拼接问题]
4 reasons for "safe left shift"
HarmonyOS.2
SaaS management system solution of smart Park: enabling the park to realize information and digital management
Common singleton mode & simple factory