GO 调度器
非常全面的一篇讲解:https://learnku.com/articles/41728
一些有意义的图片
一些理解
-
M和P的绑定关系是1:1,但M的个数不少于P的个数;
-
M中当前运行的G进行阻塞调用时,M会解除和P的绑定关系,此时P会唤醒一个空闲的M或者创建一个新的M进行绑定;当原来的M阻塞调用结束时,会优先寻找之前的P进行绑定,如果失败会去寻找一个空闲的P绑定,如果没有空闲的P,M上的G会被放入到全局队列中,M进入休眠;
-
本地队列存储G的个数有上限,256;
-
每个goroutine最多占用10ms的cpu时间片;
-
work stealing机制
runtime.schedule() { // only 1/61 of the time, check the global runnable queue for a G. 仅 1/61 的时间, 检查全局运行队列里面的 G. // if not found, check the local queue. 如果没找到, 检查本地队列. // if not found, 还是没找到 ? // try to steal from other Ps. 尝试从其他 P 偷. // if not, check the global runnable queue. 还是没有, 检查全局运行队列. // if not found, poll network. 还是没有, 轮询网络. }