Go调度器学习之系统调用的方法是什么

其他教程   发布日期:2024年12月03日   浏览次数:185

本篇内容主要讲解“Go调度器学习之系统调用的方法是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Go调度器学习之系统调用的方法是什么”吧!

1. 系统调用

下面,我们将以一个简单的文件打开的系统调用,来分析一下

  1. Go
调度器在系统调用时做了什么。

1.1 场景

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. )
  7. func main() {
  8. f, err := os.Open("./file")
  9. if err != nil {
  10. panic(err)
  11. }
  12. defer f.Close()
  13. content, err := ioutil.ReadAll(f)
  14. if err != nil {
  15. panic(err)
  16. }
  17. fmt.Println(string(content))
  18. }

如上简单的代码,读取一个名为

  1. file
的本地文件,然后打印其数据,我们通过汇编代码来分析一下其调用过程:

$ go build -gcflags "-N -l" -o main main.go
$ objdump -d main >> main.i

可以发现,在

  1. main.i
中,从
  1. main.main
函数,对于文件
  1. Open
操作的调用关系为:
  1. main.main -> os.Open -> os.openFile -> os.openFileNolog -> syscall.openat -> syscall.Syscall6.abi0 -> runtime.entersyscall.abi0
,而
  1. Syscall6
的汇编如下:

TEXT ·Syscall6(SB),NOSPLIT,$0-80
CALL runtime·entersyscall(SB)
MOVQ a1+8(FP), DI
MOVQ a2+16(FP), SI
MOVQ a3+24(FP), DX
MOVQ a4+32(FP), R10
MOVQ a5+40(FP), R8
MOVQ a6+48(FP), R9
MOVQ trap+0(FP), AX // syscall entry
SYSCALL
CMPQ AX, $0xfffffffffffff001
JLS ok6
MOVQ $-1, r1+56(FP)
MOVQ $0, r2+64(FP)
NEGQ AX
MOVQ AX, err+72(FP)
CALL runtime·exitsyscall(SB)
RET
ok6:
MOVQ AX, r1+56(FP)
MOVQ DX, r2+64(FP)
MOVQ $0, err+72(FP)
CALL runtime·exitsyscall(SB)
RET

1.2 陷入系统调用

可以发现,系统调用最终会进入到

  1. runtime.entersyscall
函数:
  1. func entersyscall() {
  2. reentersyscall(getcallerpc(), getcallersp())
  3. }

  1. runtime.entersyscall
函数会调用
  1. runtime.reentersyscall
  1. func reentersyscall(pc, sp uintptr) {
  2. _g_ := getg()
  3. // Disable preemption because during this function g is in Gsyscall status,
  4. // but can have inconsistent g->sched, do not let GC observe it.
  5. _g_.m.locks++
  6. // Entersyscall must not call any function that might split/grow the stack.
  7. // (See details in comment above.)
  8. // Catch calls that might, by replacing the stack guard with something that
  9. // will trip any stack check and leaving a flag to tell newstack to die.
  10. _g_.stackguard0 = stackPreempt
  11. _g_.throwsplit = true
  12. // Leave SP around for GC and traceback.
  13. save(pc, sp) // 保存pc和sp
  14. _g_.syscallsp = sp
  15. _g_.syscallpc = pc
  16. casgstatus(_g_, _Grunning, _Gsyscall)
  17. if _g_.syscallsp < _g_.stack.lo || _g_.stack.hi < _g_.syscallsp {
  18. systemstack(func() {
  19. print("entersyscall inconsistent ", hex(_g_.syscallsp), " [", hex(_g_.stack.lo), ",", hex(_g_.stack.hi), "]
  20. ")
  21. throw("entersyscall")
  22. })
  23. }
  24. if trace.enabled {
  25. systemstack(traceGoSysCall)
  26. // systemstack itself clobbers g.sched.{pc,sp} and we might
  27. // need them later when the G is genuinely blocked in a
  28. // syscall
  29. save(pc, sp)
  30. }
  31. if atomic.Load(&sched.sysmonwait) != 0 {
  32. systemstack(entersyscall_sysmon)
  33. save(pc, sp)
  34. }
  35. if _g_.m.p.ptr().runSafePointFn != 0 {
  36. // runSafePointFn may stack split if run on this stack
  37. systemstack(runSafePointFn)
  38. save(pc, sp)
  39. }
  40. // 一下解绑P和M
  41. _g_.m.syscalltick = _g_.m.p.ptr().syscalltick
  42. _g_.sysblocktraced = true
  43. pp := _g_.m.p.ptr()
  44. pp.m = 0
  45. _g_.m.oldp.set(pp) // 存储一下旧P
  46. _g_.m.p = 0
  47. atomic.Store(&pp.status, _Psyscall)
  48. if sched.gcwaiting != 0 {
  49. systemstack(entersyscall_gcwait)
  50. save(pc, sp)
  51. }
  52. _g_.m.locks--
  53. }

可以发现,

  1. runtime.reentersyscall
除了做一些保障性的工作外,最重要的是做了以下三件事:
  • 保存当前

    1. goroutine
    的PC和栈指针SP的内容;
  • 将当前

    1. goroutine
    的状态置为
    1. _Gsyscall
  • 将当前P的状态置为

    1. _Psyscall
    ,并解绑P和M,让当前M陷入内核的系统调用中,P被释放,可以被其他找工作的M找到并且执行剩下的
    1. goroutine

1.3 从系统调用恢复

  1. func exitsyscall() {
  2. _g_ := getg()
  3. _g_.m.locks++ // see comment in entersyscall
  4. if getcallersp() > _g_.syscallsp {
  5. throw("exitsyscall: syscall frame is no longer valid")
  6. }
  7. _g_.waitsince = 0
  8. oldp := _g_.m.oldp.ptr() // 拿到开始存储的旧P
  9. _g_.m.oldp = 0
  10. if exitsyscallfast(oldp) {
  11. if trace.enabled {
  12. if oldp != _g_.m.p.ptr() || _g_.m.syscalltick != _g_.m.p.ptr().syscalltick {
  13. systemstack(traceGoStart)
  14. }
  15. }
  16. // There's a cpu for us, so we can run.
  17. _g_.m.p.ptr().syscalltick++
  18. // We need to cas the status and scan before resuming...
  19. casgstatus(_g_, _Gsyscall, _Grunning)
  20. ...
  21. return
  22. }
  23. ...
  24. // Call the scheduler.
  25. mcall(exitsyscall0)
  26. // Scheduler returned, so we're allowed to run now.
  27. // Delete the syscallsp information that we left for
  28. // the garbage collector during the system call.
  29. // Must wait until now because until gosched returns
  30. // we don't know for sure that the garbage collector
  31. // is not running.
  32. _g_.syscallsp = 0
  33. _g_.m.p.ptr().syscalltick++
  34. _g_.throwsplit = false
  35. }

其中,

  1. exitsyscallfast
函数有以下个分支:
  • 如果旧的P还没有被其他M占用,依旧处于

    1. _Psyscall
    状态,那么直接通过
    1. wirep
    函数获取这个P,返回true;
  • 如果旧的P被占用了,那么调用

    1. exitsyscallfast_pidle
    去获取空闲的P来执行,返回true;
  • 如果没有空闲的P,则返回false;

  1. //go:nosplit
  2. func exitsyscallfast(oldp *p) bool {
  3. _g_ := getg()
  4. // Freezetheworld sets stopwait but does not retake P's.
  5. if sched.stopwait == freezeStopWait {
  6. return false
  7. }
  8. // 如果上一个P没有被其他M占用,还处于_Psyscall状态,那么直接通过wirep函数获取此P
  9. // Try to re-acquire the last P.
  10. if oldp != nil && oldp.status == _Psyscall && atomic.Cas(&oldp.status, _Psyscall, _Pidle) {
  11. // There's a cpu for us, so we can run.
  12. wirep(oldp)
  13. exitsyscallfast_reacquired()
  14. return true
  15. }
  16. // Try to get any other idle P.
  17. if sched.pidle != 0 {
  18. var ok bool
  19. systemstack(func() {
  20. ok = exitsyscallfast_pidle()
  21. if ok && trace.enabled {
  22. if oldp != nil {
  23. // Wait till traceGoSysBlock event is emitted.
  24. // This ensures consistency of the trace (the goroutine is started after it is blocked).
  25. for oldp.syscalltick == _g_.m.syscalltick {
  26. osyield()
  27. }
  28. }
  29. traceGoSysExit(0)
  30. }
  31. })
  32. if ok {
  33. return true
  34. }
  35. }
  36. return false
  37. }

  1. exitsyscallfast
函数返回false后,则会调用
  1. exitsyscall0
函数去处理:
  1. func exitsyscall0(gp *g) {
  2. casgstatus(gp, _Gsyscall, _Grunnable)
  3. dropg() // 因为当前m没有找到p,所以先解开g和m
  4. lock(&sched.lock)
  5. var _p_ *p
  6. if schedEnabled(gp) {
  7. _p_ = pidleget() // 还是尝试找一下有没有空闲的p
  8. }
  9. var locked bool
  10. if _p_ == nil { // 如果还是没有空闲p,那么把g扔到全局队列去等待调度
  11. globrunqput(gp)
  12. // Below, we stoplockedm if gp is locked. globrunqput releases
  13. // ownership of gp, so we must check if gp is locked prior to
  14. // committing the release by unlocking sched.lock, otherwise we
  15. // could race with another M transitioning gp from unlocked to
  16. // locked.
  17. locked = gp.lockedm != 0
  18. } else if atomic.Load(&sched.sysmonwait) != 0 {
  19. atomic.Store(&sched.sysmonwait, 0)
  20. notewakeup(&sched.sysmonnote)
  21. }
  22. unlock(&sched.lock)
  23. if _p_ != nil { // 如果找到了空闲p,那么就去执行,这个分支永远不会返回
  24. acquirep(_p_)
  25. execute(gp, false) // Never returns.
  26. }
  27. if locked {
  28. // Wait until another thread schedules gp and so m again.
  29. //
  30. // N.B. lockedm must be this M, as this g was running on this M
  31. // before entersyscall.
  32. stoplockedm()
  33. execute(gp, false) // Never returns.
  34. }
  35. stopm() // 这里还是没有找到空闲p的条件,停止这个m,因为没有p,所以m应该要开始找工作了
  36. schedule() // Never returns. // 通过schedule函数进行调度
  37. }

  1. exitsyscall0
函数还是会尝试找一个空闲的P,没有的话就把
  1. goroutine
扔到全局队列,然后停止这个M,并且调用
  1. schedule
函数等待调度;如果找到了空闲P,则会利用这个P去执行此
  1. goroutine

2. 小结

通过以上分析,可以发现

  1. goroutine
有关系统调用的调度还是比较简单的:
  • 在发生系统调用时会将此

    1. goroutine
    设置为
    1. _Gsyscall
    状态;
  • 并将P设置为

    1. _Psyscall
    状态,并且解绑M和P,使得这个P可以去执行其他的
    1. goroutine
    ,而M就陷入系统内核调用中了;
  • 当该M从内核调用中恢复到用户态时,会优先去获取原来的旧P,如果该旧P还未被其他M占用,则利用该P继续执行本

    1. goroutine
  • 如果没有获取到旧P,那么会尝试去P的空闲列表获取一个P来执行;

  • 如果空闲列表中没有获取到P,就会把

    1. goroutine
    扔到全局队列中,等到继续执行。

可以发现,如果系统发生着很频繁的系统调用,很可能会产生很多的M,在IO密集型的场景下,甚至会发生线程数超过10000的panic事件。

以上就是Go调度器学习之系统调用的方法是什么的详细内容,更多关于Go调度器学习之系统调用的方法是什么的资料请关注九品源码其它相关文章!