這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
說明
雖然我們一直強調golang調度器是非搶佔式。非搶佔式的一個最大壞處是無法保證公平性,如果一個g處於死迴圈狀態,那麼其他協程可能就會被餓死。 所幸的是,Golang在1.4版本中加入了搶佔式調度的邏輯,搶佔式調度必然可能在g執行的某個時刻被剝奪cpu,讓給其他協程。
實現
還記得我們之前說過Golang的sysmon協程麼,該協程會定期喚醒作系統狀態檢查,我們前面說過了它如何檢查處於Psyscall狀態的p,以便讓處於系統調用狀態的P可以被繼續執行,不至於餓死。 除了檢查這個意外,sysmon還檢查處於Prunning狀態的P,檢查它的目的就是避免這裡的某個g佔用了過多的cpu時間,並在某個時刻剝奪其cpu已耗用時間。
static uint32 retake(int64 now){ uint32 i, s, n; int64 t; P *p; Pdesc *pd; n = 0; for(i = 0; i < runtime·gomaxprocs; i++) { p = runtime·allp[i]; if(p==nil) continue; pd = &pdesc[i]; s = p->status; if(s == Psyscall) { ...... } else if(s == Prunning) { // Preempt G if it's running for more than 10ms. t = p->schedtick; if(pd->schedtick != t) { pd->schedtick = t; pd->schedwhen = now; continue; } if(pd->schedwhen + 10*1000*1000 > now) continue; // 如果自從上次發生調度時間已經超過了10ms preemptone(p); } } return n;}// 這裡的搶佔只是將g的preempt設定為true // 只有在g進行函數調用時才會檢查該標誌位 // 並進而可能發生調度,非常弱 static bool preemptone(P *p){ M *mp; G *gp; mp = p->m; if(mp == nil || mp == g->m) return false; gp = mp->curg; if(gp == nil || gp == mp->g0) return false; gp->preempt = true; // Every call in a go routine checks for stack overflow by // comparing the current stack pointer to gp->stackguard0. // Setting gp->stackguard0 to StackPreempt folds // preemption into the normal stack overflow check. gp->stackguard0 = StackPreempt; return true;}
之前我們說過在函數調用時會進行堆棧檢測,現在將gp->stackGuard0設定為StackPreempt(-1314,非常小的值),肯定會調用一次runtime.morestack,邏輯如下:
TEXT runtime·morestack(SB),NOSPLIT,$0-0 // Cannot grow scheduler stack (m->g0). get_tls(CX) MOVQ g(CX), BX MOVQ g_m(BX), BX MOVQ m_g0(BX), SI CMPQ g(CX), SI JNE 2(PC) INT $3 // Cannot grow signal stack (m->gsignal). MOVQ m_gsignal(BX), SI CMPQ g(CX), SI JNE 2(PC) INT $3 // Called from f. // Set m->morebuf to f's caller. MOVQ 8(SP), AX // f's caller's PC MOVQ AX, (m_morebuf+gobuf_pc)(BX) LEAQ 16(SP), AX // f's caller's SP MOVQ AX, (m_morebuf+gobuf_sp)(BX) get_tls(CX) MOVQ g(CX), SI MOVQ SI, (m_morebuf+gobuf_g)(BX) // Set g->sched to context in f. MOVQ 0(SP), AX // f's PC MOVQ AX, (g_sched+gobuf_pc)(SI) MOVQ SI, (g_sched+gobuf_g)(SI) LEAQ 8(SP), AX // f's SP MOVQ AX, (g_sched+gobuf_sp)(SI) MOVQ DX, (g_sched+gobuf_ctxt)(SI) MOVQ BP, (g_sched+gobuf_bp)(SI) // Call newstack on m->g0's stack. MOVQ m_g0(BX), BX MOVQ BX, g(CX) MOVQ (g_sched+gobuf_sp)(BX), SP CALL runtime·newstack(SB) MOVQ $0, 0x1003 // crash if newstack returns RET
最終調用newstack來進行堆棧擴容:
func newstack() { thisg := getg() // TODO: double check all gp. shouldn't be getg(). if thisg.m.morebuf.g.ptr().stackguard0 == stackFork { throw("stack growth after fork") } if thisg.m.morebuf.g.ptr() != thisg.m.curg { print("runtime: newstack called from g=", thisg.m.morebuf.g, "\n"+"\tm=", thisg.m, " m->curg=", thisg.m.curg, " m->g0=", thisg.m.g0, " m->gsignal=", thisg.m.gsignal, "\n") morebuf := thisg.m.morebuf traceback(morebuf.pc, morebuf.sp, morebuf.lr, morebuf.g.ptr()) throw("runtime: wrong goroutine in newstack") } gp := thisg.m.curg morebuf := thisg.m.morebuf thisg.m.morebuf.pc = 0 thisg.m.morebuf.lr = 0 thisg.m.morebuf.sp = 0 thisg.m.morebuf.g = 0 rewindmorestack(&gp.sched) // NOTE: stackguard0 may change underfoot, if another thread // is about to try to preempt gp. Read it just once and use that same // value now and below. preempt := atomicloaduintptr(&gp.stackguard0) == stackPreempt if preempt { if thisg.m.locks != 0 || thisg.m.mallocing != 0 || thisg.m.preemptoff != "" || thisg.m.p.ptr().status != _Prunning { // Let the goroutine keep running for now. // gp->preempt is set, so it will be preempted next time. gp.stackguard0 = gp.stack.lo + _StackGuard gogo(&gp.sched) // never return } } ...... // 進行重新調度 if preempt { if gp == thisg.m.g0 { throw("runtime: preempt g0") } if thisg.m.p == 0 && thisg.m.locks == 0 { throw("runtime: g is running but p is not") } if gp.preemptscan { for !castogscanstatus(gp, _Gwaiting, _Gscanwaiting) { // Likely to be racing with the GC as // it sees a _Gwaiting and does the // stack scan. If so, gcworkdone will // be set and gcphasework will simply // return. } if !gp.gcscandone { scanstack(gp) gp.gcscandone = true } gp.preemptscan = false gp.preempt = false casfrom_Gscanstatus(gp, _Gscanwaiting, _Gwaiting) casgstatus(gp, _Gwaiting, _Grunning) gp.stackguard0 = gp.stack.lo + _StackGuard gogo(&gp.sched) // never return } // Act like goroutine called runtime.Gosched. casgstatus(gp, _Gwaiting, _Grunning) // 放棄當前協程,調度新協程執行 gopreempt_m(gp) // never return }}
這裡需要注意兩個東西:
- thisg := getg():這個代表當前執行newstack()函數的堆棧,也是當前線程的g0的stack;
- gp := thisg.m.curg:這個代表的是申請棧擴容的協程,與上面的thisg不是一個東西。
因為雖然調用了newstack,但是對於stackguard0==stackPreempt的協程來說,它的目的壓根不是堆棧擴容,而是發起一次調度,所以直接進入了gopreempt_m,這裡將當前協程掛起,並發起一次schedule().