在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Go语言的线程实现模型,有三个核心的元素M、P、G,它们共同支撑起了这个线程模型的框架。其中,G 是 每一个 Goroutine 在程序运行期间,都会对应分配一个 g 对象可以重复使用,当一个 goroutine 退出时, 1. Goroutine 字段注释g 字段非常的多,我们这里分段来理解: type g struct { // Stack parameters. // stack describes the actual stack memory: [stack.lo, stack.hi). // stackguard0 is the stack pointer compared in the Go stack growth prologue. // It is stack.lo+StackGuard normally, but can be StackPreempt to trigger a preemption. // stackguard1 is the stack pointer compared in the C stack growth prologue. // It is stack.lo+StackGuard on g0 and gsignal stacks. // It is ~0 on other goroutine stacks, to trigger a call to morestackc (and crash). stack stack // offset known to runtime/cgo // 检查栈空间是否足够的值, 低于这个值会扩张, stackguard0 供 Go 代码使用 stackguard0 uintptr // offset known to liblink // 检查栈空间是否足够的值, 低于这个值会扩张, stackguard1 供 C 代码使用 stackguard1 uintptr // offset known to liblink }
// Stack describes a Go execution stack. // The bounds of the stack are exactly [lo, hi), // with no implicit data structures on either side. // 描述 goroutine 执行栈 // 栈边界为[lo, hi),左包含右不包含,即 lo≤stack<hi // 两边都没有隐含的数据结构。 type stack struct { lo uintptr // 该协程拥有的栈低位 hi uintptr // 该协程拥有的栈高位 }
如果 在 type g struct { preempt bool // preemption signal, duplicates stackguard0 = stackpreempt preemptStop bool // transition to _Gpreempted on preemption; otherwise, just deschedule preemptShrink bool // shrink stack at synchronous safe point }
type g struct { _panic *_panic // innermost panic - offset known to liblink _defer *_defer // innermost defer }
type g struct { m *m // current m; offset known to arm liblink sched gobuf goid int64 }
gobuf 结构体定义: type gobuf struct { // The offsets of sp, pc, and g are known to (hard-coded in) libmach. // 寄存器 sp, pc 和 g 的偏移量,硬编码在 libmach // // ctxt is unusual with respect to GC: it may be a // heap-allocated funcval, so GC needs to track it, but it // needs to be set and cleared from assembly, where it's // difficult to have write barriers. However, ctxt is really a // saved, live register, and we only ever exchange it between // the real register and the gobuf. Hence, we treat it as a // root during stack scanning, which means assembly that saves // and restores it doesn't need write barriers. It's still // typed as a pointer so that any other writes from Go get // write barriers. sp uintptr pc uintptr g guintptr ctxt unsafe.Pointer ret sys.Uintreg lr uintptr bp uintptr // for GOEXPERIMENT=framepointer }
调度器在将 G 由一种状态变更为另一种状态时,需要将上下文信息保存到这个 2. Goroutine 状态种类Goroutine 的状态有以下几种:
需要注意的是对于
3. Goroutine 状态转换可以看到除了上面提到的两个未使用的状态外一共有14种状态值。许多状态之间是可以进行改变的。如下图所示:
type g strcut { syscallsp uintptr // if status==Gsyscall, syscallsp = sched.sp to use during gc syscallpc uintptr // if status==Gsyscall, syscallpc = sched.pc to use during gc stktopsp uintptr // expected sp at top of stack, to check in traceback param unsafe.Pointer // passed parameter on wakeup atomicstatus uint32 stackLock uint32 // sigprof/scang lock; TODO: fold in to atomicstatus }
type g struct { waitsince int64 // approx time when the g become blocked waitreason waitReason // if status==Gwaiting }
type g struct { // asyncSafePoint is set if g is stopped at an asynchronous // safe point. This means there are frames on the stack // without precise pointer information. asyncSafePoint bool paniconfault bool // panic (instead of crash) on unexpected fault address gcscandone bool // g has scanned stack; protected by _Gscan bit in status throwsplit bool // must not split stack }
type g struct { // activeStackChans indicates that there are unlocked channels // pointing into this goroutine's stack. If true, stack // copying needs to acquire channel locks to protect these // areas of the stack. activeStackChans bool // parkingOnChan indicates that the goroutine is about to // park on a chansend or chanrecv. Used to signal an unsafe point // for stack shrinking. It's a boolean value, but is updated atomically. parkingOnChan uint8 }
type g struct { raceignore int8 // ignore race detection events sysblocktraced bool // StartTrace has emitted EvGoInSyscall about this goroutine sysexitticks int64 // cputicks when syscall has returned (for tracing) traceseq uint64 // trace event sequencer tracelastp puintptr // last P emitted an event for this goroutine lockedm muintptr sig uint32 writebuf []byte sigcode0 uintptr sigcode1 uintptr sigpc uintptr gopc uintptr // pc of go statement that created this goroutine ancestors *[]ancestorInfo // ancestor information goroutine(s) that created this goroutine (only used if debug.tracebackancestors) startpc uintptr // pc of goroutine function racectx uintptr waiting *sudog // sudog structures this g is waiting on (that have a valid elem ptr); in lock order cgoCtxt []uintptr // cgo traceback context labels unsafe.Pointer // profiler labels timer *timer // cached timer for time.Sleep selectDone uint32 // are we participating in a select and did someone win the race? }
type g struct { // Per-G GC state // gcAssistBytes is this G's GC assist credit in terms of // bytes allocated. If this is positive, then the G has credit // to allocate gcAssistBytes bytes without assisting. If this // is negative, then the G must correct this by performing // scan work. We track this in bytes to make it fast to update // and check for debt in the malloc hot path. The assist ratio // determines how this corresponds to scan work debt. gcAssistBytes int64 }
4. Goroutin 总结
参考资料: |
请发表评论