In the previous section, we created the main goroutine and put it into runNext of ALLP [0]. This section looks at how the main goroutine is scheduled to execute on the CPU

After executing CALL Runtime ·newproc(SB), proceed to CALL mstart


// start this MCALL the runtime, mstart (SB) CALL the runtime · abort (SB.)// mstart should never return
RET
Copy the code

Mstart call mstart0

The TEXT, the runtime mstart (SB), NOSPLIT | TOPFRAME, $0CALL the runtime, mstart0 RET/(SB)Copy the code

proc.go:1339

// mstart0 is the Go entry-point for new Ms.
// This must not split the stack because we may not even have stack
// bounds set up yet.
//
// May run during STW (because it doesn't have a P yet), so write
// barriers are not allowed.
//
//go:nosplit
//go:nowritebarrierrec
func mstart0(a) {
   _g_ := getg()    // _g_=g0

   osStack := _g_.stack.lo == 0 //g0 is already initialized, so osStack=false
   if osStack {
      // Initialize stack bounds from system stack.
      // Cgo may have left stack size in stack.hi.
      // minit may update the stack bounds.
      //
      // Note: these bounds may not be very accurate.
      // We set hi to &size, but there are things above
      // it. The 1024 is supposed to compensate this,
      // but is somewhat arbitrary.
      size := _g_.stack.hi
      if size == 0 {
         size = 8192 * sys.StackGuardMultiplier
      }
      _g_.stack.hi = uintptr(noescape(unsafe.Pointer(&size)))
      _g_.stack.lo = _g_.stack.hi - size + 1024
   }
   // Initialize stack guard so that we can start calling regular
   // Go code.
   _g_.stackguard0 = _g_.stack.lo + _StackGuard
   // This is the g0, so we can also call go:systemstack
   // functions, which check stackguard1.
   _g_.stackguard1 = _g_.stackguard0
   mstart1()

   // Exit this thread.
   if mStackIsSystemAllocated() {
      // Windows, Solaris, illumos, Darwin, AIX and Plan 9 always system-allocate
      // the stack, but put it in _g_.stack before mstart,
      // so the logic above hasn't set osStack yet.
      osStack = true
   }
   mexit(osStack)
}
Copy the code

Mstart0 doesn’t do anything. Mstart1

proc.go:1380

// The go:noinline is to guarantee the getcallerpc/getcallersp below are safe,
// so that we can set up g0.sched to return to the call of mstart1 above.
//go:noinline
func mstart1(a) {
   _g_ := getg()    // _g_=g0

   if_g_ ! = _g_.m.g0 { throw("Bad, runtime mstart",)}// Set up m.g0.sched as a label returning to just
   // after the mstart1 call in mstart0 above, for use by goexit0 and mcall.
   // We're never coming back to mstart1 after we call schedule,
   // so other calls can reuse the current frame.
   // And goexit0 does a gogo that needs to return from mstart1
   // and let mstart0 exit the thread.
   _g_.sched.g = guintptr(unsafe.Pointer(_g_))   // Save g0 scheduling information
   _g_.sched.pc = getcallerpc()   // Save the return address of mstart0 calling mstart1
   _g_.sched.sp = getcallersp()   // Save the top address of mstart0

   asminit()
   minit()

   // Install signal handlers; after minit so that minit can
   // prepare the thread to be able to handle the signals.
   if _g_.m == &m0 {
      mstartm0()
   }

   iffn := _g_.m.mstartfn; fn ! =nil {
      fn()
   }

   if_g_.m ! = &m0 { acquirep(_g_.m.nextp.ptr()) _g_.m.nextp =0
   }
   schedule()
}
Copy the code

The following isschedule

proc.go:3291

// One round of scheduler: find a runnable goroutine and execute it.
// Never returns.
func schedule(a) {
   (...)
   execute(gp, inheritTime)
}
Copy the code

The intermediate process is omitted. This article has a detailed analysis of the following execution

proc.go:2670

// Schedules gp to run on the current M.
// If inheritTime is true, gp inherits the remaining time in the
// current time slice. Otherwise, it starts a new time slice.
// Never returns.
//
// Write barriers are allowed because this is called immediately after
// acquiring a P in several places.
//
//go:yeswritebarrierrec
func execute(gp *g, inheritTime bool) {
   _g_ := getg()  // _g_=g0

   // Assign gp.m before entering _Grunning so running Gs have an
   // M.
   _g_.m.curg = gp // Correlate newg with m as in the previous section
   gp.m = _g_.m
   casgstatus(gp, _Grunnable, _Grunning)
   gp.waitsince = 0
   gp.preempt = false
   gp.stackguard0 = gp.stack.lo + _StackGuard
   if! inheritTime { _g_.m.p.ptr().schedtick++ }// Check whether the profiler needs to be turned on or off.
   hz := sched.profilehz
   if_g_.m.profilehz ! = hz { setThreadCPUProfiler(hz) }if trace.enabled {
      // GoSysExit has to happen when we have a P, but before GoStart.
      // So we emit it here.
      ifgp.syscallsp ! =0 && gp.sysblocktraced {
         traceGoSysExit(gp.sysexitticks)
      }
      traceGoStart()
   }

   gogo(&gp.sched)
}
Copy the code

Gogo is then called to complete the stack switch and transfer of execution rights

asm_amd64.s:257

// func gogo(buf *gobuf)
// restore state from Gobuf; longjmpTEXT runtime, gogo (SB), NOSPLIT, $0- 8 -
   MOVQ   buf+0(FP), BX     // gobuf= newg.sched BX=gobuf
   MOVQ   gobuf_g(BX), DX   // DX=newg. G
   MOVQ   0(DX), CX     // make sure g ! = nil
   JMP    gogo<>(SB)

TEXT gogo<>(SB), NOSPLIT, $0
   get_tls(CX)
   MOVQ   DX, g(CX)     // Put newg into thread-local storage, from which the executing G can be retrieved later
   MOVQ   DX, R14       // set the g register
   MOVQ   gobuf_sp(BX), SP   // restore SP SP=newg.sched. SP, complete the stack switch
   MOVQ   gobuf_ret(BX), AX  
   MOVQ   gobuf_ctxt(BX), DX
   MOVQ   gobuf_bp(BX), BP   // BP=newg.sched.bp
   MOVQ   $0, gobuf_sp(BX)   // Clear to help garbage collector
   MOVQ   $0, gobuf_ret(BX)
   MOVQ   $0, gobuf_ctxt(BX)
   MOVQ   $0, gobuf_bp(BX)
   MOVQ   gobuf_pc(BX), BX   // BX=newg.sched. PC this points to runtime.main
   JMP    BX   // Jump to Runtime. main
Copy the code
  1. usingnewg.schedTo complete the stack switch
  2. Jump toruntime.mainexecutes

proc.go:145

// The main goroutine.
func main(a) {
   g := getg()   // g=newg

   // Racectx of m0->g0 is used only as the parent of the main goroutine.
   // It must not be used for anything else.
   g.m.g0.racectx = 0

   // Max stack size is 1 GB on 64-bit, 250 MB on 32-bit.
   // Using decimal instead of binary GB and MB because
   // they look nicer in the stack overflow failure message.
   if sys.PtrSize == 8 {    // The maximum 64-bit stack can be 1G
      maxstacksize = 1000000000
   } else {
      maxstacksize = 250000000
   }

   // An upper limit for max stack size. Used to avoid random crashes
   // after calling SetMaxStack and trying to allocate a stack that is too big,
   // since stackalloc works with 32-bit sizes.
   maxstackceiling = 2 * maxstacksize

   // Allow newproc to start new Ms.
   mainStarted = true

   ifGOARCH ! ="wasm" { // no threads on wasm yet, so no sysmon
      // For runtime_syscall_doAllThreadsSyscall, we
      // register sysmon is not ready for the world to be
      // stopped.
      // Now the execution is on newg, so we need to switch to the g0 stack to create m, and run sysmon in M, without P association
      atomic.Store(&sched.sysmonStarting, 1)
      systemstack(func(a) {
         newm(sysmon, nil.- 1)})}// Lock the main goroutine onto this, the main OS thread,
   // during initialization. Most programs won't care, but a few
   // do require certain calls to be made by the main thread.
   // Those can arrange for main.main to run in the main thread
   // by calling runtime.LockOSThread during initialization
   // to preserve the lock.
   lockOSThread()

   ifg.m ! = &m0 { throw("runtime.main not on m0")
   }
   m0.doesPark = true

   // Record when the world started.
   // Must be before doInit for tracing init.
   runtimeInitTime = nanotime()
   if runtimeInitTime == 0 {
      throw("nanotime returning zero")}ifdebug.inittrace ! =0 {
      inittrace.id = getg().goid
      inittrace.active = true
   }

   doInit(&runtime_inittask) // Must be before defer.

   // Defer unlock so that runtime.Goexit during init does the unlock too.
   needUnlock := true
   defer func(a) {
      if needUnlock {
         unlockOSThread()
      }
   }()

   gcenable()

   main_init_done = make(chan bool)
   if iscgo {
      if _cgo_thread_start == nil {
         throw("_cgo_thread_start missing")}ifGOOS ! ="windows" {
         if _cgo_setenv == nil {
            throw("_cgo_setenv missing")}if _cgo_unsetenv == nil {
            throw("_cgo_unsetenv missing")}}if _cgo_notify_runtime_init_done == nil {
         throw("_cgo_notify_runtime_init_done missing")}// Start the template thread in case we enter Go from
      // a C-created thread and need to create a new thread.
      startTemplateThread()
      cgocall(_cgo_notify_runtime_init_done, nil)
   }

   doInit(&main_inittask)

   // Disable init tracing after main init done to avoid overhead
   // of collecting statistics in malloc and newproc
   inittrace.active = false

   close(main_init_done)

   needUnlock = false
   unlockOSThread()

   if isarchive || islibrary {
      // A program compiled with -buildmode=c-archive or c-shared
      // has a main, but it is not executed.
      return
   }
   fn := main_main // make an indirect call, as the linker doesn't know the address of the main package when laying down the runtime
   fn()   // Execute main
   if raceenabled {
      racefini()
   }

   // Make racy client program work: if panicking on
   // another goroutine at the same time as main returns,
   // let the other goroutine finish printing the panic trace.
   // Once it does, it will exit. See issues 3934 and 20018.
   ifatomic.Load(&runningPanicDefers) ! =0 {
      // Running deferred functions should not take long.
      for c := 0; c < 1000; c++ {
         if atomic.Load(&runningPanicDefers) == 0 {
            break
         }
         Gosched()
      }
   }
   ifatomic.Load(&panicking) ! =0 {
      gopark(nil.nil, waitReasonPanicWait, traceEvGoStop, 1)
   }

   exit(0)   // Exit from main
   for {
      var x *int32
      *x = 0}}Copy the code
  1. Create an M thread that executes sysmon alone, without P
  2. Performs initialization of the main package and the package import
  3. Execute the user’s main.main function
  4. Call exit(0) to exit the process