从源码角度看 Golang 的调度

目录

▍简单概念

▍调度器的三个抽象概念:G、M、P

▍调度的大致轮廓

下面从程序启动、调度循环、G的来源三个角度分析调度的实现。

▍进程启动时都做了什么?

▍runtime.osinit(SB)方法针对系统环境的初始化

▍runtime.schedinit(SB)调度相关的一些初始化 

▍runtime·mainPC(SB)启动监控任务 

▍最后 runtime·mstart(SB)启动调度循环

▍调度循环都做了什么

▍调度器如何开启调度循环

▍调度器如何进行调度循环

▍多个线程下如何调度

▍调度循环中如何让出CPU

▍正常完成让出CPU

▍主动让出CPU

▍抢占让出CPU

▍系统调用让出 CPU

▍待执行G的来源

▍gofunc 创建G

▍epoll 来源

 

▍看几个主动让出 CPU 的场景

▍time.Sleep

▍Mutex

▍channel

▍END


 

▍简单概念

 

调度器的三个抽象概念:G、M、P

 

  • G:代表一个 goroutine,每个 goroutine 都有自己独立的栈存放当前的运行内存及状态。可以把一个G当做一个任务。

  • M: 代表内核线程(Pthread),它本身就与一个内核线程进行绑定,goroutine 运行在M上。

  • P:代表一个处理器,可以认为一个“有运行任务”的P占了一个CPU线程的资源,且只要处于调度的时候就有P。

     

注:内核线程和 CPU 线程的区别,在系统里可以有上万个内核线程,但 CPU 线程并没有那么多,CPU 线程也就是 Top 命令里看到的 CPU0、CPU1、CPU2......的数量。

 

三者关系大致如下图:

 

640?wx_fmt=other

 

图1、图2代表2个有运行任务时的状态。M 与一个内核线程绑定,可运行的 goroutine 列表存放到P里面,然后占用了一个CPU线程来运行。

 

图3代表没有运行任务时的状态,M 依然与一个内核线程绑定,由于没有运行任务因此不占用 CPU 线程,同时也不占用P。

 

 

调度的大致轮廓

 

640?wx_fmt=other

 

 

图中表述了由 go func 触发的调度。先创建M通过M启动调度循环,然后调度循环过程中获取G来执行,执行过程中遇到图中 running G 后面几个 case 再次进入下一循环。

 

下面从程序启动、调度循环、G的来源三个角度分析调度的实现。

 

 

进程启动时都做了什么?

 

下面先看一段程序启动的代码

  1. // runtime/asm_amd64.s

  2.  
  3. TEXT runtime·rt0_go(SB),NOSPLIT,$0

  4. ......此处省略N多代码......

  5. ok:

  6. // set the per-goroutine and per-mach "registers"

  7. get_tls(BX) // 将 g0 放到 tls(thread local storage)里

  8. LEAQ runtime·g0(SB), CX

  9. MOVQ CX, g(BX)

  10. LEAQ runtime·m0(SB), AX

  11.  
  12. // save m->g0 = g0 // 将全局M0与全局G0绑定

  13. MOVQ CX, m_g0(AX)

  14. // save m0 to g0->m

  15. MOVQ AX, g_m(CX)

  16.  
  17. CLD // convention is D is always left cleared

  18. CALL runtime·check(SB)

  19.  
  20. MOVL 16(SP), AX // copy argc

  21. MOVL AX, 0(SP)

  22. MOVQ 24(SP), AX // copy argv

  23. MOVQ AX, 8(SP)

  24. CALL runtime·args(SB) // 解析命令行参数

  25. CALL runtime·osinit(SB) // 只初始化了CPU核数

  26. CALL runtime·schedinit(SB) // 内存分配器、栈、P、GC回收器等初始化

  27.  
  28. // create a new goroutine to start program

  29. MOVQ $runtime·mainPC(SB), AX //

  30. PUSHQ AX

  31. PUSHQ $0 // arg size

  32. CALL runtime·newproc(SB) // 创建一个新的G来启动runtime.main

  33. POPQ AX

  34. POPQ AX

  35.  
  36. // start this M

  37. CALL runtime·mstart(SB) // 启动M0,开始等待空闲G,正式进入调度循环

  38.  
  39. MOVL $0xf1, 0xf1 // crash

  40. RET

 

在启动过程里主要做了这三个事情(这里只跟调度相关的):

  • 初始化固定数量的P

  • 创建一个新的G来启动 runtime.main, 也就是 runtime 下的 main 方法

  • 创建全局 M0、全局 G0,启动 M0 进入第一个调度循环

     

M0 是什么?程序里会启动多个 M,第一个启动的叫 M0。

 

G0 是什么?G 分三种,第一种是执行用户任务的叫做 G,第二种执行 runtime 下调度工作的叫G0,每个M都绑定一个G0。第三种则是启动 runtime.main 用到的G。写程序接触到的基本都是第一种

 

我们按照顺序看是怎么完成上面三个事情的。

▍runtime.osinit(SB)方法针对系统环境的初始化

 

这里实质只做了一件事情,就是获取 CPU 的线程数,也就是 Top 命令里看到的 CPU0、CPU1、CPU2......的数量。 

  1. // runtime/os_linux.go

  2.  
  3. func osinit() {

  4. ncpu = getproccount()

  5. }

 

▍runtime.schedinit(SB)调度相关的一些初始化 

  1. // runtime/proc.go

  2.  
  3. // 设置最大M数量

  4. sched.maxmcount = 10000

  5.  
  6. // 初始化当前M,即全局M0

  7. mcommoninit(_g_.m)

  8.  
  9. // 查看应该启动的P数量,默认为cpu core数.

  10. // 如果设置了环境变量GOMAXPROCS则以环境变量为准,最大不得超过_MaxGomaxprocs(1024)个

  11. procs := ncpu

  12. if n, ok := atoi32(gogetenv("GOMAXPROCS")); ok && n > 0 {

  13. procs = n

  14. }

  15. if procs > _MaxGomaxprocs {

  16. procs = _MaxGomaxprocs

  17. }

  18. // 调整P数量,此时由于是初始化阶段,所以P都是新建的

  19. if procresize(procs) != nil {

  20. throw("unknown runnable goroutine during bootstrap")

  21. }

 

这里 sched.maxmcount 设置了M最大的数量,而M代表的是系统内核线程,因此可以认为一个进程最大只能启动10000个系统线程。

procresize 初始化P的数量,procs 参数为初始化的数量,而在初始化之前先做数量的判断,默认是 ncpu(与CPU核数相等)。也可以通过环境变量 GOMAXPROCS 来控制P的数量。_MaxGomaxprocs 控制了最大的P数量只能是1024。

有些人在进程初始化的时候经常用到 runtime.GOMAXPROCS() 方法,其实也是调用的 procresize 方法重新设置了最大 CPU 使用数量。

 

▍runtime·mainPC(SB)启动监控任务 

  1. // runtime/proc.go

  2.  
  3. // The main goroutine.

  4. func main() {

  5. ......

  6.  
  7. // 启动后台监控

  8. systemstack(func() {

  9. newm(sysmon, nil)

  10. })

  11.  
  12. ......

  13. }

 

在 runtime 下会启动一个全程运行的监控任务,该任务用于标记抢占执行过长时间的G,以及检测 epoll 里面是否有可执行的G。下面会详细说到。

 

最后 runtime·mstart(SB)启动调度循环

 

前面都是各种初始化操作,在这里开启了调度器的第一个调度循环。(这里启动的M就是M0)

下面来围绕G、M、P三个概念介绍 Goroutine 调度循环的运作流程。

 

调度循环都做了什么

 

640?wx_fmt=other

 

图1代表M启动的过程,把M跟一个P绑定再一起。在程序初始化的过程中说到在进程启动的最后一步启动了第一个M(即M0),这个M从全局的空闲P列表里拿到一个P,然后与其绑定。而P里面有2个管理G的链表(runq 存储等待运行的G列表,gfree 存储空闲的G列表),M启动后等待可执行的G。

图2代表创建G的过程。创建完一个G先扔到当前P的 runq 待运行队列里。在图3的执行过程里,M从绑定的P的 runq 列表里获取一个G来执行。当执行完成后,图4的流程里把G仍到 gfree 队列里。注意此时G并没有销毁(只重置了G的栈以及状态),当再次创建G的时候优先从 gfree 列表里获取,这样就起到了复用G的作用,避免反复与系统交互创建内存。

M即启动后处于一个自循环状态,执行完一个G之后继续执行下一个G,反复上面的图2~图4过程。当第一个M正在繁忙而又有新的G需要执行时,会再开启一个M来执行。

下面详细看下调度循环的实现。

调度器如何开启调度循环

先看一下M的启动过程(M0启动是个特殊的启动过程,也是第一个启动的M,由汇编实现的初始化后启动,而后续的M创建以及启动则是Go代码实现)。 

  1. // runtime/proc.go

  2.  
  3. func startm(_p_ *p, spinning bool) {

  4. lock(&sched.lock)

  5. if _p_ == nil {

  6. // 从空闲P里获取一个

  7. _p_ = pidleget()

  8.  
  9. ......

  10. }

  11. // 获取一个空闲的m

  12. mp := mget()

  13. unlock(&sched.lock)

  14. // 如果没有空闲M,则new一个

  15. if mp == nil {

  16. var fn func()

  17. if spinning {

  18. // The caller incremented nmspinning, so set m.spinning in the new M.

  19. fn = mspinning

  20. }

  21. newm(fn, _p_)

  22. return

  23. }

  24.  
  25. ......

  26.  
  27. // 唤醒M

  28. notewakeup(&mp.park)

  29. }

  30.  
  31. func newm(fn func(), _p_ *p) {

  32. // 创建一个M对象,且与P关联

  33. mp := allocm(_p_, fn)

  34. // 暂存P

  35. mp.nextp.set(_p_)

  36. mp.sigmask = initSigmask

  37.  
  38. ......

  39.  
  40. execLock.rlock() // Prevent process clone.

  41. // 创建系统内核线程

  42. newosproc(mp, unsafe.Pointer(mp.g0.stack.hi))

  43. execLock.runlock()

  44. }

  45.  
  46. // runtime/os_linux.go

  47. func newosproc(mp *m, stk unsafe.Pointer) {

  48. // Disable signals during clone, so that the new thread starts

  49. // with signals disabled. It will enable them in minit.

  50. var oset sigset

  51. sigprocmask(_SIG_SETMASK, &sigset_all, &oset)

  52. ret := clone(cloneFlags, stk, unsafe.Pointer(mp), unsafe.Pointer(mp.g0), unsafe.Pointer(funcPC(mstart)))

  53. sigprocmask(_SIG_SETMASK, &oset, nil)

  54. }

  55.  
  56. func allocm(_p_ *p, fn func()) *m {

  57. ......

  58.  
  59. mp := new(m)

  60. mp.mstartfn = fn // 设置启动函数

  61. mcommoninit(mp) // 初始化m

  62.  
  63. // 创建g0

  64. // In case of cgo or Solaris, pthread_create will make us a stack.

  65. // Windows and Plan 9 will layout sched stack on OS stack.

  66. if iscgo || GOOS == "solaris" || GOOS == "windows" || GOOS == "plan9" {

  67. mp.g0 = malg(-1)

  68. } else {

  69. mp.g0 = malg(8192 * sys.StackGuardMultiplier)

  70. }

  71. // 把新创建的g0与M做关联

  72. mp.g0.m = mp

  73.  
  74. ......

  75.  
  76. return mp

  77. }

  78.  
  79. func mstart() {

  80. ......

  81.  
  82. mstart1()

  83. }

  84.  
  85. func mstart1() {

  86.  
  87. ......

  88.  
  89. // 进入调度循环(阻塞不返回)

  90. schedule()

  91. }

 

非M0的启动首先从 startm 方法开始启动,要进行调度工作必须有调度处理器P,因此先从空闲的P链表里获取一个P,在 newm 方法创建一个M与P绑定。

newm 方法中通过 newosproc 新建一个内核线程,并把内核线程与M以及 mstart 方法进行关联,这样内核线程执行时就可以找到M并且找到启动调度循环的方法。最后 schedule 启动调度循环

allocm 方法中创建M的同时创建了一个G与自己关联,这个G就是我们在上面说到的g0。为什么M要关联一个g0?因为 runtime 下执行一个G也需要用到栈空间来完成调度工作,而拥有执行栈的地方只有G,因此需要为每个执行线程里配置一个g0。

▍调度器如何进行调度循环

调用 schedule 进入调度器的调度循环后,在这个方法里永远不再返回。下面看下实现。 

  1. // runtime/proc.go

  2.  
  3. func schedule() {

  4. _g_ := getg()

  5.  
  6. // 进入gc MarkWorker 工作模式

  7. if gp == nil && gcBlackenEnabled != 0 {

  8. gp = gcController.findRunnableGCWorker(_g_.m.p.ptr())

  9. }

  10. if gp == nil {

  11. // Check the global runnable queue once in a while to ensure fairness.

  12. // Otherwise two goroutines can completely occupy the local runqueue

  13. // by constantly respawning each other.

  14. // 每处理n个任务就去全局队列获取G任务,确保公平

  15. if _g_.m.p.ptr().schedtick%61 == 0 && sched.runqsize > 0 {

  16. lock(&sched.lock)

  17. gp = globrunqget(_g_.m.p.ptr(), 1)

  18. unlock(&sched.lock)

  19. }

  20. }

  21. // 从P本地获取

  22. if gp == nil {

  23. gp, inheritTime = runqget(_g_.m.p.ptr())

  24. if gp != nil && _g_.m.spinning {

  25. throw("schedule: spinning with local work")

  26. }

  27. }

  28. // 从其它地方获取G,如果获取不到则沉睡M,并且阻塞在这里,直到M被再次使用

  29. if gp == nil {

  30. gp, inheritTime = findrunnable() // blocks until work is available

  31. }

  32.  
  33. ......

  34.  
  35. // 执行找到的G

  36. execute(gp, inheritTime)

  37. }

  38.  
  39. // 从P本地获取一个可运行的G

  40. func runqget(_p_ *p) (gp *g, inheritTime bool) {

  41. // If there's a runnext, it's the next G to run.

  42. // 优先从runnext里获取一个G,如果没有则从runq里获取

  43. for {

  44. next := _p_.runnext

  45. if next == 0 {

  46. break

  47. }

  48. if _p_.runnext.cas(next, 0) {

  49. return next.ptr(), true

  50. }

  51. }

  52.  
  53. // 从队头获取

  54. for {

  55. h := atomic.Load(&_p_.runqhead) // load-acquire, synchronize with other consumers

  56. t := _p_.runqtail

  57. if t == h {

  58. return nil, false

  59. }

  60. gp := _p_.runq[h%uint32(len(_p_.runq))].ptr()

  61. if atomic.Cas(&_p_.runqhead, h, h+1) { // cas-release, commits consume

  62. return gp, false

  63. }

  64. }

  65. }

  66.  
  67. // 从其它地方获取G

  68. func findrunnable() (gp *g, inheritTime bool) {

  69. ......

  70.  
  71. // 从本地队列获取

  72. if gp, inheritTime := runqget(_p_); gp != nil {

  73. return gp, inheritTime

  74. }

  75.  
  76. // 全局队列获取

  77. if sched.runqsize != 0 {

  78. lock(&sched.lock)

  79. gp := globrunqget(_p_, 0)

  80. unlock(&sched.lock)

  81. if gp != nil {

  82. return gp, false

  83. }

  84. }

  85.  
  86. // 从epoll里取

  87. if netpollinited() && sched.lastpoll != 0 {

  88. if gp := netpoll(false); gp != nil { // non-blocking

  89. ......

  90.  
  91. return gp, false

  92. }

  93. }

  94.  
  95. ......

  96.  
  97. // 尝试4次从别的P偷

  98. for i := 0; i < 4; i++ {

  99. for enum := stealOrder.start(fastrand()); !enum.done(); enum.next() {

  100. if sched.gcwaiting != 0 {

  101. goto top

  102. }

  103. stealRunNextG := i > 2 // first look for ready queues with more than 1 g

  104. // 在这里开始针对P进行偷取操作

  105. if gp := runqsteal(_p_, allp[enum.position()], stealRunNextG); gp != nil {

  106. return gp, false

  107. }

  108. }

  109. }

  110. }

  111.  
  112. // 尝试从全局runq中获取G

  113. // 在"sched.runqsize/gomaxprocs + 1"、"max"、"len(_p_.runq))/2"三个数字中取最小的数字作为获取的G数量

  114. func globrunqget(_p_ *p, max int32) *g {

  115. if sched.runqsize == 0 {

  116. return nil

  117. }

  118.  
  119. n := sched.runqsize/gomaxprocs + 1

  120. if n > sched.runqsize {

  121. n = sched.runqsize

  122. }

  123. if max > 0 && n > max {

  124. n = max

  125. }

  126. if n > int32(len(_p_.runq))/2 {

  127. n = int32(len(_p_.runq)) / 2

  128. }

  129.  
  130. sched.runqsize -= n

  131. if sched.runqsize == 0 {

  132. sched.runqtail = 0

  133. }

  134.  
  135. gp := sched.runqhead.ptr()

  136. sched.runqhead = gp.schedlink

  137. n--

  138. for ; n > 0; n-- {

  139. gp1 := sched.runqhead.ptr()

  140. sched.runqhead = gp1.schedlink

  141. runqput(_p_, gp1, false) // 放到本地P里

  142. }

  143. return gp

  144. }

schedule 中首先尝试从P本地队列中获取(runqget)一个可执行的G,如果没有则从其它地方获取(findrunnable),最终通过 execute 方法执行G。

runqget 先通过 runnext 拿到待运行G,没有的话,再从 runq 里面取。

findrunnable 从全局队列、epoll、别的P里获取。(后面会扩展分析实现)

在调度的开头出还做了一个小优化:每处理一些任务之后,就优先从全局队列里获取任务,以保障公平性,防止由于每个P里的G过多,而全局队列里的任务一直得不到执行机会。

这里用到了一个关键方法getg(),runtime 的代码里大量使用该方法,它由汇编实现,该方法就是获取当前运行的G,具体实现不再这里阐述。

多个线程下如何调度

 

抛出一个问题:每个P里面的G执行时间是不可控的,如果多个P同时在执行,会不会出现有的P里面的G执行不完,有的P里面几乎没有G可执行呢?

这就要从M的自循环过程中如何获取G、归还G的行为说起了,先看图:

 

640?wx_fmt=other

 

图中可以看出有两种途径:1.借助全局队列 sched.runq 作为中介,本地P里的G太多的话就放全局里,G太少的话就从全局取。2.全局列表里没有的话直接从P1里偷取(steal)。(更多M在执行的话,同样的原理,这里就只拿2个来举例)

第1种途径实现如下: 

  1. // runtime/proc.go

  2.  
  3. func runqput(_p_ *p, gp *g, next bool) {

  4. if randomizeScheduler && next && fastrand()%2 == 0 {

  5. next = false

  6. }

  7.  
  8. // 尝试把G添加到P的runnext节点,这里确保runnext只有一个G,如果之前已经有一个G则踢出来放到runq里

  9. if next {

  10. retryNext:

  11. oldnext := _p_.runnext

  12. if !_p_.runnext.cas(oldnext, guintptr(unsafe.Pointer(gp))) {

  13. goto retryNext

  14. }

  15. if oldnext == 0 {

  16. return

  17. }

  18. // 把老的g踢出来,在下面放到runq里

  19. gp = oldnext.ptr()

  20. }

  21.  
  22. retry:

  23. // 如果_p_.runq队列不满,则放到队尾就结束了。

  24. // 试想如果不放到队尾而放到队头里会怎样?如果频繁的创建G则可能后面的G总是不被执行,对后面的G不公平

  25. h := atomic.Load(&_p_.runqhead) // load-acquire, synchronize with consumers

  26. t := _p_.runqtail

  27. if t-h < uint32(len(_p_.runq)) {

  28. _p_.runq[t%uint32(len(_p_.runq))].set(gp)

  29. atomic.Store(&_p_.runqtail, t+1) // store-release, makes the item available for consumption

  30. return

  31. }

  32. //如果队列满了,尝试把G和当前P里的一部分runq放到全局队列

  33. //因为操作全局需要加锁,所以名字里带个slow

  34. if runqputslow(_p_, gp, h, t) {

  35. return

  36. }

  37. // the queue is not full, now the put above must succeed

  38. goto retry

  39. }

  40.  
  41. func runqputslow(_p_ *p, gp *g, h, t uint32) bool {

  42. var batch [len(_p_.runq)/2 + 1]*g

  43.  
  44. // First, grab a batch from local queue.

  45. n := t - h

  46. n = n / 2

  47. if n != uint32(len(_p_.runq)/2) {

  48. throw("runqputslow: queue is not full")

  49. }

  50. // 从runq头部开始取出一半的runq放到临时变量batch里

  51. for i := uint32(0); i < n; i++ {

  52. batch[i] = _p_.runq[(h+i)%uint32(len(_p_.runq))].ptr()

  53. }

  54. if !atomic.Cas(&_p_.runqhead, h, h+n) { // cas-release, commits consume

  55. return false

  56. }

  57. // 把要put的g也放进batch去

  58. batch[n] = gp

  59.  
  60. if randomizeScheduler {

  61. for i := uint32(1); i <= n; i++ {

  62. j := fastrandn(i + 1)

  63. batch[i], batch[j] = batch[j], batch[i]

  64. }

  65. }

  66.  
  67. // 把取出来的一半runq组成链表

  68. for i := uint32(0); i < n; i++ {

  69. batch[i].schedlink.set(batch[i+1])

  70. }

  71.  
  72. // 将一半的runq放到global队列里,一次多转移一些省得转移频繁

  73. lock(&sched.lock)

  74. globrunqputbatch(batch[0], batch[n], int32(n+1))

  75. unlock(&sched.lock)

  76. return true

  77. }

  78.  
  79. func globrunqputbatch(ghead *g, gtail *g, n int32) {

  80. gtail.schedlink = 0

  81. if sched.runqtail != 0 {

  82. sched.runqtail.ptr().schedlink.set(ghead)

  83. } else {

  84. sched.runqhead.set(ghead)

  85. }

  86. sched.runqtail.set(gtail)

  87. sched.runqsize += n

  88. }

 

runqput 方法归还执行完的G,runq 定义是 runq [256]guintptr,有固定的长度,因此当前P里的待运行G超过256的时候说明过多了,则执行 runqputslow 方法把一半G扔给全局G链表,globrunqputbatch 连接全局链表的头尾指针。

但可能别的P里面并没有超过256,就不会放到全局G链表里,甚至可能一直维持在不到256个。这就借助第2个途径了:

第2种途径实现如下: 

  1. // runtime/proc.go

  2.  
  3. // 从其它地方获取G

  4. func findrunnable() (gp *g, inheritTime bool) {

  5. ......

  6.  
  7. // 尝试4次从别的P偷

  8. for i := 0; i < 4; i++ {

  9. for enum := stealOrder.start(fastrand()); !enum.done(); enum.next() {

  10. if sched.gcwaiting != 0 {

  11. goto top

  12. }

  13. stealRunNextG := i > 2 // first look for ready queues with more than 1 g

  14. // 在这里开始针对P进行偷取操作

  15. if gp := runqsteal(_p_, allp[enum.position()], stealRunNextG); gp != nil {

  16. return gp, false

  17. }

  18. }

  19. }

  20. }

 

从别的P里面"偷取"一些G过来执行了。runqsteal 方法实现了"偷取"操作。 

  1. // runtime/proc.go

  2.  
  3. // 偷取P2一半到本地运行队列,失败则返回nil

  4. func runqsteal(_p_, p2 *p, stealRunNextG bool) *g {

  5. t := _p_.runqtail

  6. n := runqgrab(p2, &_p_.runq, t, stealRunNextG)

  7. if n == 0 {

  8. return nil

  9. }

  10. n--

  11. // 返回尾部的一个G

  12. gp := _p_.runq[(t+n)%uint32(len(_p_.runq))].ptr()

  13. if n == 0 {

  14. return gp

  15. }

  16. h := atomic.Load(&_p_.runqhead) // load-acquire, synchronize with consumers

  17. if t-h+n >= uint32(len(_p_.runq)) {

  18. throw("runqsteal: runq overflow")

  19. }

  20. atomic.Store(&_p_.runqtail, t+n) // store-release, makes the item available for consumption

  21. return gp

  22. }

  23.  
  24. // 从P里获取一半的G,放到batch里

  25. func runqgrab(_p_ *p, batch *[256]guintptr, batchHead uint32, stealRunNextG bool) uint32 {

  26. for {

  27. // 计算一半的数量

  28. h := atomic.Load(&_p_.runqhead) // load-acquire, synchronize with other consumers

  29. t := atomic.Load(&_p_.runqtail) // load-acquire, synchronize with the producer

  30. n := t - h

  31. n = n - n/2

  32.  
  33. ......

  34.  
  35. // 将偷到的任务转移到本地P队列里

  36. for i := uint32(0); i < n; i++ {

  37. g := _p_.runq[(h+i)%uint32(len(_p_.runq))]

  38. batch[(batchHead+i)%uint32(len(batch))] = g

  39. }

  40. if atomic.Cas(&_p_.runqhead, h, h+n) { // cas-release, commits consume

  41. return n

  42. }

  43. }

  44. }

上面可以看出从别的P里面偷(steal)了一半,这样就足够运行了。有了“偷取”操作也就充分利用了多线程的资源。

 

调度循环中如何让出CPU

 

▍正常完成让出CPU

绝大多数场景下我们程序都是执行完一个G,再执行另一个G,那我们就看下G是如何被执行以及执行完如何退出的。

先看G如何被执行: 

  1. // runtime/proc.go

  2.  
  3. func execute(gp *g, inheritTime bool) {

  4. _g_ := getg()

  5.  
  6. casgstatus(gp, _Grunnable, _Grunning)

  7.  
  8. ......

  9.  
  10. // 真正的执行G,切换到该G的栈帧上执行(汇编实现)

  11. gogo(&gp.sched)

  12. }

execute 方法先更改G的状态为_Grunning 表示运行中,最终给 gogo 方法做实际的执行操作。而 gogo 方法则是汇编实现。再来看下 gogo 方法的实现: 

  1. // runtime.asm_amd64.s

  2.  
  3. TEXT runtime·gogo(SB), NOSPLIT, $16-8

  4. MOVQ buf+0(FP), BX // gobuf 把0偏移的8个字节给BX寄存器, gobuf结构的前8个字节就是SP指针

  5.  
  6. // If ctxt is not nil, invoke deletion barrier before overwriting.

  7. MOVQ gobuf_ctxt(BX), AX // 在把gobuf的ctxt变量给AX寄存器

  8. TESTQ AX, AX // 判断AX寄存器是否为空,传进来gp.sched的话肯定不为空了,因此JZ nilctxt不跳转

  9. JZ nilctxt

  10. LEAQ gobuf_ctxt(BX), AX

  11. MOVQ AX, 0(SP)

  12. MOVQ $0, 8(SP)

  13. CALL runtime·writebarrierptr_prewrite(SB)

  14. MOVQ buf+0(FP), BX

  15.  
  16. nilctxt: // 下面则是函数栈的BP SP指针移动,最后进入到指定的代码区域

  17. MOVQ gobuf_g(BX), DX

  18. MOVQ 0(DX), CX // make sure g != nil

  19. get_tls(CX)

  20. MOVQ DX, g(CX)

  21. MOVQ gobuf_sp(BX), SP // restore SP

  22. MOVQ gobuf_ret(BX), AX

  23. MOVQ gobuf_ctxt(BX), DX

  24. MOVQ gobuf_bp(BX), BP

  25. MOVQ $0, gobuf_sp(BX) // clear to help garbage collector

  26. MOVQ $0, gobuf_ret(BX)

  27. MOVQ $0, gobuf_ctxt(BX)

  28. MOVQ $0, gobuf_bp(BX)

  29. MOVQ gobuf_pc(BX), BX // PC指针指向退出时要执行的函数地址

  30. JMP BX // 跳转到执行代码处

 
  1. // runtime/runtime2.go

  2.  
  3. type gobuf struct {

  4. // The offsets of sp, pc, and g are known to (hard-coded in) libmach.

  5. //

  6. // ctxt is unusual with respect to GC: it may be a

  7. // heap-allocated funcval so write require a write barrier,

  8. // but gobuf needs to be cleared from assembly. We take

  9. // advantage of the fact that the only path that uses a

  10. // non-nil ctxt is morestack. As a result, gogo is the only

  11. // place where it may not already be nil, so gogo uses an

  12. // explicit write barrier. Everywhere else that resets the

  13. // gobuf asserts that ctxt is already nil.

  14. sp uintptr

  15. pc uintptr

  16. g guintptr

  17. ctxt unsafe.Pointer // this has to be a pointer so that gc scans it

  18. ret sys.Uintreg

  19. lr uintptr

  20. bp uintptr // for GOEXPERIMENT=framepointer

  21. }

 

gogo 方法传的参数注意是 gp.sched,而这个结构体里可以看到保存了熟悉的函数栈寄存器 SP/PC/BP,能想到是把执行栈传了进去(既然是执行一个G,当然要把执行栈传进去了)。可以看到在 gogo 函数中实质就只是做了函数栈指针的移动。

这个执行G的操作,熟悉函数调用的函数栈的基本原理的人想必有些印象(如果不熟悉请自行搜索),执行一个G其实就是执行函数一样切换到对应的函数栈帧上。

C语言里栈帧创建的时候有个IP寄存器指向"return address",即主调函数的一条指令的地址, 被调函数退出的时候通过该指针回到调用函数里。在Go语言里有个PC寄存器指向退出函数。那么下PC寄存器指向的是哪里?我们回到创建G的地方看下代码:

 

  1. // runtime/proc.go

  2.  
  3. func newproc1(fn *funcval, argp *uint8, narg int32, nret int32, callerpc uintptr) *g {

  4. ......

  5.  
  6. // 从当前P里面复用一个空闲G

  7. newg := gfget(_p_)

  8. // 如果没有空闲G则新建一个,默认堆大小为_StackMin=2048 bytes

  9. if newg == nil {

  10. newg = malg(_StackMin)

  11. casgstatus(newg, _Gidle, _Gdead)

  12. // 把新创建的G添加到全局allg里

  13. allgadd(newg) // publishes with a g->status of Gdead so GC scanner doesn't look at uninitialized stack.

  14. }

  15.  
  16. ......

  17.  
  18. newg.sched.sp = sp

  19. newg.stktopsp = sp

  20. newg.sched.pc = funcPC(goexit) + sys.PCQuantum // 记录当前任务的pc寄存器为goexit方法,用于当执行G结束后找到退出方法,从而再次进入调度循环 // +PCQuantum so that previous instruction is in same function

  21. newg.sched.g = guintptr(unsafe.Pointer(newg))

  22. gostartcallfn(&newg.sched, fn)

  23. newg.gopc = callerpc

  24. newg.startpc = fn.fn

  25.  
  26. .......

  27.  
  28. return newg

  29. }

 

代码中可以看到,给G的执行环境里的 pc 变量赋值了一个 goexit 的函数地址,也就是说G正常执行完退出时执行的是 goexit 函数。再看下该函数的实现: 

  1. // runtime/asm_amd64.s

  2.  
  3. // The top-most function running on a goroutine

  4. // returns to goexit+PCQuantum.

  5. TEXT runtime·goexit(SB),NOSPLIT,$0-0

  6. BYTE $0x90 // NOP

  7. CALL runtime·goexit1(SB) // does not return

  8. // traceback from goexit1 must hit code range of goexit

  9.   BYTE  $0x90  // NOP

 
  1. // runtime/proc.go

  2.  
  3. // G执行结束后回到这里放到P的本地队列里

  4. func goexit1() {

  5. if raceenabled {

  6. racegoend()

  7. }

  8. if trace.enabled {

  9. traceGoEnd()

  10. }

  11. // 切换到g0来释放G

  12. mcall(goexit0)

  13. }

  14.  
  15. // g0下当G执行结束后回到这里放到P的本地队列里

  16. func goexit0(gp *g) {

  17. ......

  18.  
  19. gfput(_g_.m.p.ptr(), gp)

  20. schedule()

  21. }

代码中切换到了G0下执行了 schedule 方法,再次进度了下一轮调度循环。

以上就是正常执行一个G并正常退出的实现。

主动让出CPU

在实际场景中还有一些没有执行完成的G,而又需要临时停止执行,比如 time.Sleep、IO阻塞等等,就需要挂起该G,把CPU让出给别人使用。在 runtime 下面有个 gopark 方法,看下实现:// runtime/proc.go

  1.  
  2. func gopark(unlockf func(*g, unsafe.Pointer) bool, lock unsafe.Pointer, reason string, traceEv byte, traceskip int) {

  3. mp := acquirem()

  4. gp := mp.curg

  5. status := readgstatus(gp)

  6. if status != _Grunning && status != _Gscanrunning {

  7. throw("gopark: bad g status")

  8. }

  9. mp.waitlock = lock

  10. mp.waitunlockf = *(*unsafe.Pointer)(unsafe.Pointer(&unlockf))

  11. gp.waitreason = reason

  12. mp.waittraceev = traceEv

  13. mp.waittraceskip = traceskip

  14. releasem(mp)

  15. // can't do anything that might move the G between Ms here.

  16. // mcall 在M里从当前正在运行的G切换到g0

  17. // park_m 在切换到的g0下先把传过来的G切换为_Gwaiting状态挂起该G

  18. // 调用回调函数waitunlockf()由外层决定是否等待解锁,返回true则等待解锁不在执行G,返回false则不等待解锁继续执行

  19. mcall(park_m)

  20. }

  21.  
  1. // runtime/stubs.go

  2.  
  3. // mcall switches from the g to the g0 stack and invokes fn(g),

  4. // where g is the goroutine that made the call.

  5. // mcall saves g's current PC/SP in g->sched so that it can be restored later.

  6. ......

  7. func mcall(fn func(*g))

 

 
  1. // runtime/proc.go

  2.  
  3. func park_m(gp *g) {

  4. _g_ := getg() // 此处获得的是g0,而不是gp

  5.  
  6. if trace.enabled {

  7. traceGoPark(_g_.m.waittraceev, _g_.m.waittraceskip)

  8. }

  9.  
  10. casgstatus(gp, _Grunning, _Gwaiting)

  11. dropg() // 把g0从M的"当前运行"里剥离出来

  12.  
  13. if _g_.m.waitunlockf != nil {

  14. fn := *(*func(*g, unsafe.Pointer) bool)(unsafe.Pointer(&_g_.m.waitunlockf))

  15. ok := fn(gp, _g_.m.waitlock)

  16. _g_.m.waitunlockf = nil

  17. _g_.m.waitlock = nil

  18. if !ok { // 如果不需要等待解锁,则切换到_Grunnable状态并直接执行G

  19. if trace.enabled {

  20. traceGoUnpark(gp, 2)

  21. }

  22. casgstatus(gp, _Gwaiting, _Grunnable)

  23. execute(gp, true) // Schedule it back, never returns.

  24. }

  25. }

  26. schedule()

  27. }

 

gopark 是进行调度出让CPU资源的方法,里面有个方法 mcall(),注释里这样描述:

 

从当前运行的G切换到g0的运行栈上,然后调用fn(g),这里被调用的G是调用mcall方法时的G。mcall方法保存当前运行的G的 PC/SP 到 g->sched 里,因此该G可以在以后被重新恢复执行.

 

在本章开始介绍初始化过程中有提到M创建的时候绑定了一个 g0,调度工作是运行在 g0 的栈上的。mcall 方法通过 g0 先把当前调用的G的执行栈暂存到 g->sched 变量里,然后切换到 g0 的执行栈上执行 park_m。park_m 方法里把 gp 的状态从 _Grunning 切换到 _Gwaiting 表明进入到等待唤醒状态,此时休眠G的操作就完成了。接下来既然G休眠了,CPU 线程总不能闲下来,在 park_m 方法里又可以看到 schedule 方法,开始进入到到一轮调度循环了。

 

park_m 方法里还有段小插曲,进入调度循环之前还有个对 waitunlockf 方法的判断,该方法意思是如果解锁不成功则调用 execute 方法继续执行之前的 G,而该方法永远不会 return,也就不会再次进入下一次调度。也就是说给外部一个控制是否要进行下一个调度的选择。

 

抢占让出CPU

 

回想在 runtime.main()里面有单独启动了一个监控任务,方法是 sysmon。看下该方法: 

  1. // runtime/proc.go

  2.  
  3. func sysmon() {

  4. ......

  5.  
  6. for {

  7. // delay参数用于控制for循环的间隔,不至于无限死循环。

  8. // 控制逻辑是前50次每次sleep 20微秒,超过50次则每次翻2倍,直到最大10毫秒

  9. if idle == 0 { // start with 20us sleep...

  10. delay = 20

  11. } else if idle > 50 { // start doubling the sleep after 1ms...

  12. delay *= 2

  13. }

  14. if delay > 10*1000 { // up to 10ms

  15. delay = 10 * 1000

  16. }

  17. usleep(delay)

  18.  
  19. lastpoll := int64(atomic.Load64(&sched.lastpoll))

  20. now := nanotime()

  21. if lastpoll != 0 && lastpoll+10*1000*1000 < now {

  22. atomic.Cas64(&sched.lastpoll, uint64(lastpoll), uint64(now))

  23. gp := netpoll(false) // non-blocking - returns list of goroutines

  24. if gp != nil {

  25. ......

  26.  
  27. incidlelocked(-1)

  28. // 把epoll ready的G列表注入到全局runq里

  29. injectglist(gp)

  30. incidlelocked(1)

  31. }

  32. }

  33.  
  34. // retake P's blocked in syscalls

  35. // and preempt long running G's

  36. if retake(now) != 0 {

  37. idle = 0

  38. } else {

  39. idle++

  40. }

  41.  
  42. ......

  43. }

  44. }

  45.  
  46. func retake(now int64) uint32 {

  47. n := 0

  48. for i := int32(0); i < gomaxprocs; i++ {

  49. _p_ := allp[i] // 从所有P里面去找

  50. if _p_ == nil {

  51. continue

  52. }

  53. pd := &_p_.sysmontick

  54. s := _p_.status

  55. if s == _Psyscall {

  56.  
  57. ......

  58.  
  59. } else if s == _Prunning { // 针对正在运行的P

  60. // Preempt G if it's running for too long.

  61. t := int64(_p_.schedtick)

  62. if int64(pd.schedtick) != t {

  63. pd.schedtick = uint32(t)

  64. pd.schedwhen = now

  65. continue

  66. }

  67. // 如果已经超过forcePreemptNS(10ms),则抢占

  68. if pd.schedwhen+forcePreemptNS > now {

  69. continue

  70. }

  71. // 抢占P

  72. preemptone(_p_)

  73. }

  74. }

  75. return uint32(n)

  76. }

  77.  
  78. func preemptone(_p_ *p) bool {

  79. mp := _p_.m.ptr()

  80. if mp == nil || mp == getg().m {

  81. return false

  82. }

  83. // 找到当前正在运行的G

  84. gp := mp.curg

  85. if gp == nil || gp == mp.g0 {

  86. return false

  87. }

  88. // 标记抢占状态

  89. gp.preempt = true

  90.  
  91. // Every call in a go routine checks for stack overflow by

  92. // comparing the current stack pointer to gp->stackguard0.

  93. // Setting gp->stackguard0 to StackPreempt folds

  94. // preemption into the normal stack overflow check.

  95. // G里面的每一次调用都会比较当前栈指针与 gp->stackguard0 来检查堆栈溢出

  96. // 设置 gp->stackguard0 为 StackPreempt 来触发正常的堆栈溢出检测

  97. gp.stackguard0 = stackPreempt

  98. return true

  99. }

sysmon() 方法处于无限 for 循环,整个进程的生命周期监控着。retake()方法每次对所有的P遍历检查超过10ms的还在运行的G,如果有超过10ms的则通过 preemptone()进行抢占,但是要注意这里只把 gp.stackguard0赋值了一个 stackPreempt,并没有做让出 CPU 的操作,因此这里的抢占实质只是一个”标记“抢占。那么真正停止G执行的操作在哪里? 

  1. // runtime/stack.go

  2.  
  3. func newstack(ctxt unsafe.Pointer) {

  4. ......

  5.  
  6. // NOTE: stackguard0 may change underfoot, if another thread

  7. // is about to try to preempt gp. Read it just once and use that same

  8. // value now and below.

  9. // 这里的逻辑是为G的抢占做的判断。

  10. // 判断是否是抢占引发栈扩张,如果 gp.stackguard0 == stackPreempt 则说明是抢占触发的栈扩张

  11. preempt := atomic.Loaduintptr(&gp.stackguard0) == stackPreempt

  12.  
  13. ......

  14.  
  15. //如果判断可以抢占, 则继续判断是否GC引起的, 如果是则对G的栈空间执行标记处理(扫描根对象)然后继续运行,

  16. //如果不是GC引起的则调用gopreempt_m函数完成抢占.

  17. if preempt {

  18. ......

  19.  
  20. // 停止当前运行状态的G,最后放到全局runq里,释放M

  21. // 这里会进入schedule循环.阻塞到这里

  22. gopreempt_m(gp) // never return

  23. }

  24.  
  25. ......

  26. }

 // runtime/proc.go 
  1.  
  2. func goschedImpl(gp *g) {

  3. status := readgstatus(gp)

  4. if status&^_Gscan != _Grunning {

  5. dumpgstatus(gp)

  6. throw("bad g status")

  7. }

  8. casgstatus(gp, _Grunning, _Grunnable)

  9. dropg()

  10. lock(&sched.lock)

  11. globrunqput(gp)

  12. unlock(&sched.lock)

  13.  
  14. schedule()

  15. }

我们都知道 Go 的调度是非抢占式的,要想实现G不被长时间,就只能主动触发抢占,而 Go 触发抢占的实际就是在栈扩张的时候,在 newstack 新创建栈空间的时候检测是否有抢占标记(也就是 gp.stackguard0是否等于 stackPreempt),如果有则通过 goschedImpl 方法再次进入到熟悉的 schedule 调度循环。

 

系统调用让出 CPU

 

我们程序都跑在系统上面,就绕不开与系统的交互。那么当我们的 Go 程序做系统调用的时候,系统的方法不确定会阻塞多久,而我们程序又不知道运行的状态该怎么办?

 

在 Go 中并没有直接对系统内核函数调用,而是封装了个 syscall.Syscall 方法,先看下实现:

  1. // syscall/syscall_unix.go

  2.  
  3. func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)

 
  1. // syscall/asm_linux_amd64.s

  2.  
  3. TEXT ·Syscall(SB),NOSPLIT,$0-56

  4. CALL runtime·entersyscall(SB)

  5. MOVQ a1+8(FP), DI

  6. MOVQ a2+16(FP), SI

  7. MOVQ a3+24(FP), DX

  8. MOVQ $0, R10

  9. MOVQ $0, R8

  10. MOVQ $0, R9

  11. MOVQ trap+0(FP), AX // syscall entry

  12. SYSCALL // 进行系统调用

  13. CMPQ AX, $0xfffffffffffff001

  14. JLS ok

  15. MOVQ $-1, r1+32(FP)

  16. MOVQ $0, r2+40(FP)

  17. NEGQ AX

  18. MOVQ AX, err+48(FP)

  19. CALL runtime·exitsyscall(SB)

  20. RET

  21. ok:

  22. MOVQ AX, r1+32(FP)

  23. MOVQ DX, r2+40(FP)

  24. MOVQ $0, err+48(FP)

  25. CALL runtime·exitsyscall(SB)

  26.   RET

 

在汇编代码中看出先是执行了 runtime·entersyscall 方法,然后进行系统调用,最后执行了 runtime·exitsyscall(SB),从字面意思看是进入系统调用之前先执行一些逻辑,退出系统调用之后执行一堆逻辑。看下具体实现:

 

  1. // runtime/proc.go

  2.  
  3. func entersyscall(dummy int32) {

  4. reentersyscall(getcallerpc(unsafe.Pointer(&dummy)), getcallersp(unsafe.Pointer(&dummy)))

  5. }

  6.  
  7. func reentersyscall(pc, sp uintptr) {

  8. ......

  9.  
  10. // Leave SP around for GC and traceback.

  11. // 保存执行现场

  12. save(pc, sp)

  13. _g_.syscallsp = sp

  14. _g_.syscallpc = pc

  15. // 切换到系统调用状态

  16. casgstatus(_g_, _Grunning, _Gsyscall)

  17.  
  18. ......

  19.  
  20. // Goroutines must not split stacks in Gsyscall status (it would corrupt g->sched).

  21. // We set _StackGuard to StackPreempt so that first split stack check calls morestack.

  22. // Morestack detects this case and throws.

  23. _g_.stackguard0 = stackPreempt

  24. _g_.m.locks--

  25. }

 

进入系统调用前先保存执行现场,然后切换到_Gsyscall 状态,最后标记抢占,等待被抢占走。

  1. // runtime/proc.go

  2.  
  3. func exitsyscall(dummy int32) {

  4. ......

  5.  
  6. // Call the scheduler.

  7. mcall(exitsyscall0)

  8.  
  9. ......

  10. }

  11.  
  12. func exitsyscall0(gp *g) {

  13. _g_ := getg()

  14.  
  15. casgstatus(gp, _Gsyscall, _Grunnable)

  16. dropg()

  17. lock(&sched.lock)

  18. // 获取一个空闲的P,如果没有则放到全局队列里,如果有则执行

  19. _p_ := pidleget()

  20. if _p_ == nil {

  21. globrunqput(gp) // 如果没有P就放到全局队列里,等待有资源时执行

  22. } else if atomic.Load(&sched.sysmonwait) != 0 {

  23. atomic.Store(&sched.sysmonwait, 0)

  24. notewakeup(&sched.sysmonnote)

  25. }

  26. unlock(&sched.lock)

  27. if _p_ != nil {

  28. acquirep(_p_)

  29. execute(gp, false) // Never returns. // 如果找到空闲的P则直接执行

  30. }

  31. if _g_.m.lockedg != nil {

  32. // Wait until another thread schedules gp and so m again.

  33. stoplockedm()

  34. execute(gp, false) // Never returns.

  35. }

  36. stopm()

  37. schedule() // Never returns. // 没有P资源执行,就继续下一轮调度循环

  38. }

 

系统调用退出时,切到 G0 下把G状态切回来,如果有可执行的P则直接执行,如果没有则放到全局队列里,等待调度,最后又看到了熟悉的 schedule 进入下一轮调度循环。

 

 

待执行G的来源

 

gofunc 创建G

 

当开启一个 Goroutine 的时候用到 go func()这样的语法,在 runtime 下其实调用的就是 newproc 方法。

 

  1. // runtime/proc.go

  2.  
  3. func newproc(siz int32, fn *funcval) {

  4. argp := add(unsafe.Pointer(&fn), sys.PtrSize)

  5. pc := getcallerpc(unsafe.Pointer(&siz))

  6. systemstack(func() {

  7. newproc1(fn, (*uint8)(argp), siz, 0, pc)

  8. })

  9. }

  10.  
  11. func newproc1(fn *funcval, argp *uint8, narg int32, nret int32, callerpc uintptr) *g {

  12. ......

  13.  
  14. _p_ := _g_.m.p.ptr()

  15. // 从当前P里面复用一个空闲G

  16. newg := gfget(_p_)

  17. // 如果没有空闲G则新建一个,默认堆大小为_StackMin=2048 bytes

  18. if newg == nil {

  19. newg = malg(_StackMin)

  20. casgstatus(newg, _Gidle, _Gdead)

  21. // 把新创建的G添加到全局allg里

  22. allgadd(newg) // publishes with a g->status of Gdead so GC scanner doesn't look at uninitialized stack.

  23. }

  24.  
  25. ......

  26.  
  27. if isSystemGoroutine(newg) {

  28. atomic.Xadd(&sched.ngsys, +1)

  29. }

  30. newg.gcscanvalid = false

  31. casgstatus(newg, _Gdead, _Grunnable)

  32.  
  33. // 把G放到P里的待运行队列,第三参数设置为true,表示要放到runnext里,作为优先要执行的G

  34. runqput(_p_, newg, true)

  35.  
  36. // 如果有其它空闲P则尝试唤醒某个M来执行

  37. // 如果有M处于自璇等待P或G状态,放弃。

  38. // NOTE: sched.nmspinning!=0说明正在有M被唤醒,这里判断sched.nmspinnin==0时才进入wakep是防止同时唤醒多个M

  39. if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 && mainStarted {

  40. wakep()

  41. }

  42.  
  43. ......

  44.  
  45. return newg

  46. }

 

newproc1方法中 gfget 先从空闲的G列表获取一个G对象,没有则创建一个新的G对象,然后 runqput 放到当前P待运行队列里。

 

epoll 来源

 

回想上面分析抢占以及多线程下如何调度时都见到一个 netpoll 方法,这个方法就是从系统内核获取已经有数据的时间,然后映射到对应的G标记 ready。下面看实现:

 

 
  1. // runtime/proc.go

  2.  
  3. func netpoll(block bool) *g {

  4. ......

  5. var events [128]epollevent

  6. retry:

  7. n := epollwait(epfd, &events[0], int32(len(events)), waitms)

  8. if n < 0 {

  9. if n != -_EINTR {

  10. println("runtime: epollwait on fd", epfd, "failed with", -n)

  11. throw("runtime: netpoll failed")

  12. }

  13. goto retry

  14. }

  15. var gp guintptr

  16. for i := int32(0); i < n; i++ {

  17. ev := &events[i]

  18. if ev.events == 0 {

  19. continue

  20. }

  21. var mode int32

  22. if ev.events&(_EPOLLIN|_EPOLLRDHUP|_EPOLLHUP|_EPOLLERR) != 0 {

  23. mode += 'r'

  24. }

  25. if ev.events&(_EPOLLOUT|_EPOLLHUP|_EPOLLERR) != 0 {

  26. mode += 'w'

  27. }

  28. if mode != 0 {

  29. pd := *(**pollDesc)(unsafe.Pointer(&ev.data))

  30.  
  31. netpollready(&gp, pd, mode)

  32. }

  33. }

  34. if block && gp == 0 {

  35. goto retry

  36. }

  37. return gp.ptr()

  38. }

  39.  
  40. func netpollready(gpp *guintptr, pd *pollDesc, mode int32) {

  41. var rg, wg guintptr

  42. if mode == 'r' || mode == 'r'+'w' {

  43. rg.set(netpollunblock(pd, 'r', true))

  44. }

  45. if mode == 'w' || mode == 'r'+'w' {

  46. wg.set(netpollunblock(pd, 'w', true))

  47. }

  48. if rg != 0 {

  49. rg.ptr().schedlink = *gpp

  50. *gpp = rg

  51. }

  52. if wg != 0 {

  53. wg.ptr().schedlink = *gpp

  54. *gpp = wg

  55. }

  56. }

  57.  
  58. // 解锁pd wait状态,标记为pdReady,并返回

  59. func netpollunblock(pd *pollDesc, mode int32, ioready bool) *g {

  60. gpp := &pd.rg

  61. if mode == 'w' {

  62. gpp = &pd.wg

  63. }

  64.  
  65. for {

  66. old := *gpp

  67. if old == pdReady {

  68. return nil

  69. }

  70. if old == 0 && !ioready {

  71. // Only set READY for ioready. runtime_pollWait

  72. // will check for timeout/cancel before waiting.

  73. return nil

  74. }

  75. var new uintptr

  76. if ioready {

  77. new = pdReady

  78. }

  79. // 变量pd.rg在netpollblock的时候已经指向了运行pd的G,因此old其实指向G的指针,而不是pdWait等等的状态指针了

  80. if atomic.Casuintptr(gpp, old, new) {

  81. if old == pdReady || old == pdWait {

  82. old = 0

  83. }

  84. return (*g)(unsafe.Pointer(old))

  85. }

  86. }

  87. }

 

首先 epollwait 从内核获取到一批 event,也就拿到了有收到就绪的 FD。netpoll 的返回值是一个G链表,在该方法里只是把要被唤醒的G标记 ready,然后交给外部处理,例如 sysmon 中的代码:



// runtime/proc.go

  1.  
  2. func sysmon() {

  3. ......

  4.  
  5. for {

  6. ......

  7.  
  8. lastpoll := int64(atomic.Load64(&sched.lastpoll))

  9. now := nanotime()

  10. if lastpoll != 0 && lastpoll+10*1000*1000 < now {

  11. atomic.Cas64(&sched.lastpoll, uint64(lastpoll), uint64(now))

  12. gp := netpoll(false) // non-blocking - returns list of goroutines

  13. if gp != nil {

  14. ......

  15.  
  16. incidlelocked(-1)

  17. // 把epoll ready的G列表注入到全局runq里

  18. injectglist(gp)

  19. incidlelocked(1)

  20. }

  21. }

  22.  
  23. ......

  24. }

  25. }

  26.  
  27. // 把G列表注入到全局runq里

  28. func injectglist(glist *g) {

  29. ......

  30.  
  31. lock(&sched.lock)

  32. var n int

  33. for n = 0; glist != nil; n++ {

  34. gp := glist

  35. glist = gp.schedlink.ptr()

  36. casgstatus(gp, _Gwaiting, _Grunnable)

  37. globrunqput(gp)

  38. }

  39.  
  40. ......

  41. }

 

netpoll 返回的链表交给了 injectglist,然后其实是放到了全局 rung 队列中,等待被调度。

 

epoll 内容较多,本章主要围绕调度的话题讨论,在这里就不展开分析。

 

看几个主动让出 CPU 的场景

 

time.Sleep

 

当代码中调用 time.Sleep 的时候我们是要 black 住程序不在继续往下执行,此时该 goroutine 不会做其他事情了,理应把 CPU 资源释放出来,下面看下实现:

 

  1. // runtime/time.go

  2.  
  3. func timeSleep(ns int64) {

  4. if ns <= 0 {

  5. return

  6. }

  7.  
  8. t := getg().timer

  9. if t == nil {

  10. t = new(timer)

  11. getg().timer = t

  12. }

  13. *t = timer{} // 每个定时任务都创建一个timer

  14. t.when = nanotime() + ns

  15. t.f = goroutineReady // 记录唤醒该G的方法,唤醒时通过该方法执行唤醒

  16. t.arg = getg() // 把timer与当前G关联,时间到了唤醒时通过该参数找到所在的G

  17. lock(&timers.lock)

  18. addtimerLocked(t) // 把timer添加到最小堆里

  19. goparkunlock(&timers.lock, "sleep", traceEvGoSleep, 2) // 切到G0让出CPU,进入休眠

  20. }

 

 
  1. // runtime/proc.go

  2.  
  3. func goparkunlock(lock *mutex, reason string, traceEv byte, traceskip int) {

  4. gopark(parkunlock_c, unsafe.Pointer(lock), reason, traceEv, traceskip)

  5. }

 

timeSleep 函数里通过 addtimerLocked 把定时器加入到 timer 管理器(timer 通过最小堆的数据结构存放每个定时器,在这不做详细说明)后,再通过 goparkunlock 实现把当前G休眠,这里看到了上面提到的 gopark 方法进行调度循环的上下文切换。

 

上面介绍的是一个G如何进入到休眠状态的过程,该例子是个定时器,当时间到了的话,当前G就要被唤醒继续执行了。下面就介绍下唤醒的流程。

 

返回到最开始 timeSleep 方法里在进入调度方法之前有一个 addtimerLocked 方法,看下这个方法做了什么。

 

  1. // runtime/time.go

  2.  
  3. func addtimerLocked(t *timer) {

  4. // when must never be negative; otherwise timerproc will overflow

  5. // during its delta calculation and never expire other runtime timers.

  6. if t.when < 0 {

  7. t.when = 1<<63 - 1

  8. }

  9. t.i = len(timers.t)

  10. timers.t = append(timers.t, t) //将当前timer添加到timer管理器里

  11. siftupTimer(t.i)

  12.  
  13. ......

  14.  
  15. // 如果没有启动timer管理定时器,则启动。timerproc只会启动一次,即全局timer管理器

  16. if !timers.created {

  17. timers.created = true

  18. go timerproc()

  19. }

  20. }

 

 
  1. // runtime/time.go

  2.  
  3. // Timerproc runs the time-driven events.

  4. // It sleeps until the next event in the timers heap.

  5. // If addtimer inserts a new earlier event, it wakes timerproc early.

  6. func timerproc() {

  7. timers.gp = getg()

  8. for {

  9. lock(&timers.lock)

  10. timers.sleeping = false

  11. now := nanotime()

  12. delta := int64(-1)

  13. for {

  14. if len(timers.t) == 0 {

  15. delta = -1

  16. break

  17. }

  18. t := timers.t[0]

  19. delta = t.when - now

  20. if delta > 0 {

  21. break

  22. }

  23. if t.period > 0 {

  24. // leave in heap but adjust next time to fire

  25. t.when += t.period * (1 + -delta/t.period)

  26. siftdownTimer(0)

  27. } else {

  28. // remove from heap

  29. last := len(timers.t) - 1

  30. if last > 0 {

  31. timers.t[0] = timers.t[last]

  32. timers.t[0].i = 0

  33. }

  34. timers.t[last] = nil

  35. timers.t = timers.t[:last]

  36. if last > 0 {

  37. siftdownTimer(0)

  38. }

  39. t.i = -1 // mark as removed

  40. }

  41. f := t.f

  42. arg := t.arg

  43. seq := t.seq

  44. unlock(&timers.lock)

  45. if raceenabled {

  46. raceacquire(unsafe.Pointer(t))

  47. }

  48. f(arg, seq)

  49. lock(&timers.lock)

  50. }

  51. ......

  52. }

  53. }

 

在 addtimerLocked 方法的最下面有个逻辑在运行期间开启了'全局时间事件驱动器'timerproc,该方法会全程遍历最小堆,寻找最早进入 timer 管理器的定时器,然后唤醒。他是怎么找到要唤醒哪个G的?回头看下 timeSleep 方法里把当时正在执行的G以及唤醒方法 goroutineReady 带到了每个定时器里,而在 timerproc 则通过找到期的定时器执行f(arg, seq)


即通过 goroutineReady 方法唤醒。方法调用过程: goroutineReady() -> ready()

 

 
 
  1. /// runtime/time.go

  2.  
  3. func goroutineReady(arg interface{}, seq uintptr) {

  4. goready(arg.(*g), 0)

  5. }

 

 
 
  1. // runtime/proc.go

  2.  
  3. func goready(gp *g, traceskip int) {

  4. systemstack(func() {

  5. ready(gp, traceskip, true)

  6. })

  7. }

  8.  
  9. // Mark gp ready to run.

  10. func ready(gp *g, traceskip int, next bool) {

  11. if trace.enabled {

  12. traceGoUnpark(gp, traceskip)

  13. }

  14.  
  15. status := readgstatus(gp)

  16.  
  17. // Mark runnable.

  18. _g_ := getg()

  19. _g_.m.locks++ // disable preemption because it can be holding p in a local var

  20. if status&^_Gscan != _Gwaiting {

  21. dumpgstatus(gp)

  22. throw("bad g->status in ready")

  23. }

  24.  
  25. // status is Gwaiting or Gscanwaiting, make Grunnable and put on runq

  26. casgstatus(gp, _Gwaiting, _Grunnable)

  27. runqput(_g_.m.p.ptr(), gp, next)

  28.  
  29. ......

  30. }

 

在上面的方法里可以看到先把休眠的G从_Gwaiting 切换到_Grunnable 状态,表明已经可运行。然后通过 runqput 方法把G放到P的待运行队列里,就进入到调度器的调度循环里了。

 

总结:time.Sleep 想要进入阻塞(休眠)状态,其实是通过 gopark 方法给自己标记个_Gwaiting 状态,然后把自己所占用的CPU线程资源给释放出来,继续执行调度任务,调度其它的G来运行。而唤醒是通过把G更改回_Grunnable 状态后,然后把G放入到P的待运行队列里等待执行。通过这点还可以看出休眠中的G其实并不占用 CPU 资源,最多是占用内存,是个很轻量级的阻塞。

 

Mutex

 

 
 
  1. // sync/mutex.go

  2.  
  3. func (m *Mutex) Lock() {

  4. // Fast path: grab unlocked mutex.

  5. // 首先尝试抢锁,如果抢到则直接返回,并标记mutexLocked状态

  6. if atomic.CompareAndSwapInt32(&m.state, 0, mutexLocked) {

  7. if race.Enabled {

  8. race.Acquire(unsafe.Pointer(m))

  9. }

  10. return

  11. }

  12.  
  13. var waitStartTime int64

  14. starving := false

  15. awoke := false

  16. iter := 0

  17. old := m.state

  18. for {

  19. // Don't spin in starvation mode, ownership is handed off to waiters

  20. // so we won't be able to acquire the mutex anyway.

  21. // 尝试自璇,但有如下几个条件跳过自璇,这里的自璇是用户态自璇,基本lock的cpu消耗都耗到这里了

  22. // 1.不在饥饿模式自璇

  23. // 2.超过4次循环,则不再自璇. (runtime_canSpin里面)

  24. // 3.全部P空闲时,不自璇.(runtime_canSpin里面)

  25. // 4.当前P里无运行G时,不自璇.(runtime_canSpin里面)

  26. if old&(mutexLocked|mutexStarving) == mutexLocked && runtime_canSpin(iter) {

  27. // Active spinning makes sense.

  28. // Try to set mutexWoken flag to inform Unlock

  29. // to not wake other blocked goroutines.

  30. if !awoke && old&mutexWoken == 0 && old>>mutexWaiterShift != 0 &&

  31. atomic.CompareAndSwapInt32(&m.state, old, old|mutexWoken) {

  32. awoke = true

  33. }

  34. runtime_doSpin() // doSpin其实就是用户态自璇30次

  35. iter++

  36. old = m.state

  37. continue

  38. }

  39.  
  40. ......

  41.  
  42. if atomic.CompareAndSwapInt32(&m.state, old, new) {

  43. ......

  44.  
  45. runtime_SemacquireMutex(&m.sema, queueLifo) // 这里会再次自璇几次,然后最后切换到g0把G标记_Gwaiting状态阻塞在这里

  46. starving = starving || runtime_nanotime()-waitStartTime > starvationThresholdNs // 如果锁等了1毫秒才被唤醒,才会标记为饥饿模式

  47. old = m.state

  48.  
  49. ......

  50. } else {

  51. old = m.state

  52. }

  53. }

  54.  
  55. if race.Enabled {

  56. race.Acquire(unsafe.Pointer(m))

  57. }

  58. }

 

 
 
  1. // runtime/sema.go

  2.  
  3. func sync_runtime_Semacquire(addr *uint32) {

  4. semacquire1(addr, false, semaBlockProfile)

  5. }

  6.  
  7. func semacquire1(addr *uint32, lifo bool, profile semaProfileFlags) {

  8. ......

  9.  
  10. for {

  11. ......

  12.  
  13. // Any semrelease after the cansemacquire knows we're waiting

  14. // (we set nwait above), so go to sleep.

  15. root.queue(addr, s, lifo) // 把当前锁的信息存起来以便以后唤醒时找到当前G,G是在queue里面获取的。

  16. goparkunlock(&root.lock, "semacquire", traceEvGoBlockSync, 4) // 进行休眠,然后阻塞在这里

  17. if s.ticket != 0 || cansemacquire(addr) {

  18. break

  19. }

  20. }

  21. }

  22.  
  23. // queue adds s to the blocked goroutines in semaRoot.

  24. func (root *semaRoot) queue(addr *uint32, s *sudog, lifo bool) {

  25. s.g = getg() // 这里记录了当前的G,以便唤醒的时候找到要被唤醒的G

  26. s.elem = unsafe.Pointer(addr)

  27. s.next = nil

  28. s.prev = nil

  29.  
  30. var last *sudog

  31. pt := &root.treap

  32. for t := *pt; t != nil; t = *pt {

  33. ......

  34.  
  35. last = t

  36. if uintptr(unsafe.Pointer(addr)) < uintptr(t.elem) {

  37. pt = &t.prev

  38. } else {

  39. pt = &t.next

  40. }

  41. }

  42.  
  43.   ......

 

Mutex.Lock 方法通过调用 runtime_SemacquireMutex 最终还是调用 goparkunlock 实现把G进入到休眠状态。在进入休眠之前先把自己加入到队列里 root.queue(addr, s, lifo),在 queue 方法里,记录了当前的G,以便以后找到并唤醒。

 

 
 
  1. // sync/mutex.go

  2.  
  3. func (m *Mutex) Unlock() {

  4. ......

  5.  
  6. if new&mutexStarving == 0 { // 如果不是饥饿模式

  7. old := new

  8. for {

  9. ......

  10.  
  11. if atomic.CompareAndSwapInt32(&m.state, old, new) {

  12. runtime_Semrelease(&m.sema, false) // 唤醒锁

  13. return

  14. }

  15. old = m.state

  16. }

  17. } else {

  18. // Starving mode: handoff mutex ownership to the next waiter.

  19. // Note: mutexLocked is not set, the waiter will set it after wakeup.

  20. // But mutex is still considered locked if mutexStarving is set,

  21. // so new coming goroutines won't acquire it.

  22. runtime_Semrelease(&m.sema, true) // 唤醒锁

  23. }

  24. }

 

 
 
  1. // runtime/sema.go

  2.  
  3. func sync_runtime_Semrelease(addr *uint32, handoff bool) {

  4. semrelease1(addr, handoff)

  5. }

  6.  
  7. func semrelease1(addr *uint32, handoff bool) {

  8. root := semroot(addr)

  9. s, t0 := root.dequeue(addr)

  10. if s != nil {

  11. atomic.Xadd(&root.nwait, -1)

  12. }

  13.  
  14. ......

  15.  
  16. if s != nil { // May be slow, so unlock first

  17. ......

  18.  
  19. readyWithTime(s, 5)

  20. }

  21. }

  22.  
  23. func readyWithTime(s *sudog, traceskip int) {

  24. if s.releasetime != 0 {

  25. s.releasetime = cputicks()

  26. }

  27. goready(s.g, traceskip)

  28. }

 

Mutex. Unlock 方法通过调用 runtime_Semrelease 最终还是调用 goready 实现把G唤醒。

 

 

channel

 

 
 
  1. // runtime/chan.go

  2.  
  3. func chansend(c *hchan, ep unsafe.Pointer, block bool, callerpc uintptr) bool {

  4. // 寻找一个等待中的receiver,直接把值传给这个receiver,绕过下面channel buffer,

  5. // 避免从sender buffer->chan buffer->receiver buffer,而是直接sender buffer->receiver buffer,仍然做了内存copy

  6. if sg := c.recvq.dequeue(); sg != nil {

  7. send(c, sg, ep, func() { unlock(&c.lock) }, 3)

  8. return true

  9. }

  10.  
  11. // 如果没有receiver等待:

  12. // 如果当前chan里的元素个数小于环形队列大小(也就是chan还没满),则把内存拷贝到channel buffer里,然后直接返回。

  13. // 注意dataqsiz是允许为0的,当为0时,也不存在该if里面的内存copy

  14. if c.qcount < c.dataqsiz {

  15. // Space is available in the channel buffer. Enqueue the element to send.

  16. qp := chanbuf(c, c.sendx) // 获取即将要写入的chan buffer的指针地址

  17. if raceenabled {

  18. raceacquire(qp)

  19. racerelease(qp)

  20. }

  21. // 把元素内存拷贝进去.

  22. // 注意这里产生了一次内存copy,也就是说如果没有receiver的话,就一定会产生内存拷贝

  23. typedmemmove(c.elemtype, qp, ep)

  24. c.sendx++ // 发送索引+1

  25. if c.sendx == c.dataqsiz {

  26. c.sendx = 0

  27. }

  28. c.qcount++ // 队列元素计数器+1

  29. unlock(&c.lock)

  30. return true

  31. }

  32.  
  33. if !block { // 如果是非阻塞的,到这里就可以结束了

  34. unlock(&c.lock)

  35. return false

  36. }

  37.  
  38. // ########下面是进入阻塞模式的如何实现阻塞的处理逻辑

  39.  
  40. // Block on the channel. Some receiver will complete our operation for us.

  41. // 把元素相关信息、当前的G信息打包到一个sudog里,然后扔进send队列

  42. gp := getg()

  43. mysg := acquireSudog()

  44. mysg.releasetime = 0

  45. if t0 != 0 {

  46. mysg.releasetime = -1

  47. }

  48. // No stack splits between assigning elem and enqueuing mysg

  49. // on gp.waiting where copystack can find it.

  50. mysg.elem = ep

  51. mysg.waitlink = nil

  52. mysg.g = gp // 把当前G也扔进sudog里,用于别人唤醒该G的时候找到该G

  53. mysg.selectdone = nil

  54. mysg.c = c

  55. gp.waiting = mysg // 记录当前G正在等待的sudog

  56. gp.param = nil

  57. c.sendq.enqueue(mysg)

  58. // 切换到g0,把当前G切换到_Gwaiting状态,然后唤醒lock.

  59. // 此时当前G被阻塞了,P就继续执行其它G去了.

  60. goparkunlock(&c.lock, "chan send", traceEvGoBlockSend, 3)

  61.  
  62. ......

  63.  
  64. return true

  65. }

  66.  
  67. func send(c *hchan, sg *sudog, ep unsafe.Pointer, unlockf func(), skip int) {

  68. ......

  69.  
  70. gp := sg.g

  71. unlockf()

  72. gp.param = unsafe.Pointer(sg)

  73. if sg.releasetime != 0 {

  74. sg.releasetime = cputicks()

  75. }

  76. goready(gp, skip+1)

  77. }

 

 

当给一个 chan 发送消息的时候,实质触发的方法是 chansend。在该方法里不是先进入休眠状态。

 

1)如果此时有接收者接收这个 chan 的消息则直接把数据通过 send 方法扔给接收者,并唤醒接收者的G,然后当前G则继续执行。

 

2)如果没有接收者,就把数据 copy 到 chan 的临时内存里,且内存没有满就继续执行当前G。

 

3)如果没有接收者且 chan 满了,依然是通过 goparkunlock 方法进入休眠。在休眠前把当前的G相关信息存到队列(sendq)以便有接收者接收数据的时候唤醒当前G。

 

 
 
  1. func chanrecv(c *hchan, ep unsafe.Pointer, block bool) (selected, received bool) {

  2. ......

  3.  
  4. if sg := c.sendq.dequeue(); sg != nil {

  5. // Found a waiting sender. If buffer is size 0, receive value

  6. // directly from sender. Otherwise, receive from head of queue

  7. // and add sender's value to the tail of the queue (both map to

  8. // the same buffer slot because the queue is full).

  9. // 寻找一个正在等待的sender

  10. // 如果buffer size是0,则尝试直接从sender获取(这种情况是在环形队列长度(dataqsiz)为0的时候出现)

  11. // 否则(buffer full的时候)从队列head接收,并且帮助sender在队列满时的阻塞的元素信息拷贝到队列里,然后将sender的G状态切换为_Grunning,这样sender就不阻塞了。

  12. recv(c, sg, ep, func() { unlock(&c.lock) }, 3)

  13. return true, true

  14. }

  15.  
  16. // 如果有数据则从channel buffer里获取数据后返回(此时环形队列长度dataqsiz!=0)

  17. if c.qcount > 0 {

  18. // Receive directly from queue

  19. qp := chanbuf(c, c.recvx) // 获取即将要读取的chan buffer的指针地址

  20. if raceenabled {

  21. raceacquire(qp)

  22. racerelease(qp)

  23. }

  24. if ep != nil {

  25. typedmemmove(c.elemtype, ep, qp) // copy元素数据内存到channel buffer

  26. }

  27. typedmemclr(c.elemtype, qp)

  28. c.recvx++

  29. if c.recvx == c.dataqsiz {

  30. c.recvx = 0

  31. }

  32. c.qcount--

  33. unlock(&c.lock)

  34. return true, true

  35. }

  36.  
  37. if !block {

  38. unlock(&c.lock)

  39. return false, false

  40. }

  41.  
  42. // ##########下面是无任何数据准备把当前G切换为_Gwaiting状态的逻辑

  43.  
  44. // no sender available: block on this channel.

  45. gp := getg()

  46. mysg := acquireSudog()

  47. mysg.releasetime = 0

  48. if t0 != 0 {

  49. mysg.releasetime = -1

  50. }

  51. // No stack splits between assigning elem and enqueuing mysg

  52. // on gp.waiting where copystack can find it.

  53. mysg.elem = ep

  54. mysg.waitlink = nil

  55. gp.waiting = mysg

  56. mysg.g = gp

  57. mysg.selectdone = nil

  58. mysg.c = c

  59. gp.param = nil

  60. c.recvq.enqueue(mysg)

  61. // 释放了锁,然后把当前G切换为_Gwaiting状态,阻塞在这里等待有数据进来被唤醒

  62. goparkunlock(&c.lock, "chan receive", traceEvGoBlockRecv, 3)

  63.  
  64. ......

  65.  
  66. return true, !closed

  67. }

  68.  
  69. func recv(c *hchan, sg *sudog, ep unsafe.Pointer, unlockf func(), skip int) {

  70. ......

  71.  
  72. sg.elem = nil

  73. gp := sg.g

  74. unlockf()

  75. gp.param = unsafe.Pointer(sg)

  76. if sg.releasetime != 0 {

  77. sg.releasetime = cputicks()

  78. }

  79. goready(gp, skip+1)

  80. }

 

 

chanrecv 方法是在 chan 接收者的地方调用的方法。

 

1)如果有发送者被休眠,则取出数据然后唤醒发送者,当前接收者的G拿到数据继续执行。

 

2)如果没有等待的发送者就看下有没有发送的数据还没被接收,有的话就直接取出数据然后返回,当前接收者的G拿到数据继续执行。(注意:这里取的数据不是正在等待的 sender 的数据,而是从 chan 的开头的内存取,如果是 sender 的数据则读出来的数据顺序就乱了)

 

3)如果即没有发送者,chan 里也没数据就通过 goparkunlock 进行休眠,在休眠之前把当前的G相关信息存到 recvq 里面,以便有数据时找到要唤醒的G。

 

 

END

 

640?wx_fmt=png

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值