@@ -353,6 +353,184 @@ func Gosched() {
353353 mcall (gosched_m )
354354}
355355
356+ // Yield cooperatively yields if, and only if, the scheduler is "busy".
357+ //
358+ // This can be called by any work wishing to utilize strictly spare capacity
359+ // while minimizing the degree to which it delays other work from being promptly
360+ // scheduled.
361+ //
362+ // Yield is intended to have very low overhead, particularly in its no-op case
363+ // where there is idle capacity in the scheduler and the caller does not need to
364+ // yield. This should allow it to be called often, such as in the body of tight
365+ // loops, in any tasks wishing to yield promptly to any waiting work.
366+ //
367+ // When there is waiting work, the yielding goroutine may briefly be rescheduled
368+ // after it, or may, in some cases, be parked in a waiting 'yield' state until
369+ // the scheduler next has spare capacity to resume it. Yield does not guarantee
370+ // fairness or starvation-prevention: once a goroutine Yields(), it may remain
371+ // parked until the scheduler next has idle capacity. This means Yield can block
372+ // for unbounded durations in the presence of sustained over-saturation; callers
373+ // are responsible for deciding where to Yield() to avoid priority inversions.
374+ //
375+ // Yield will never park if the calling goroutine is locked to an OS thread.
376+ func Yield () {
377+ // Common/fast case: do nothing if npidle is non-zero meaning there is
378+ // an idle P so no reason to yield this one. Doing only this check here keeps
379+ // Yield inlineable (~70 of 80 as of writing).
380+ if sched .npidle .Load () == 0 {
381+ maybeYield ()
382+ }
383+ }
384+
385+ // maybeYield is called by Yield if npidle is zero, meaning there are no idle Ps
386+ // and thus there may be work to which the caller should yield. Such work could
387+ // be on this local runq of the caller's P, on the global runq, in the runq of
388+ // some other P, or even in the form of ready conns waiting to be noticed by a
389+ // netpoll which would then ready runnable goroutines.
390+ //
391+ // Keeping this function extremely cheap is essential: it must be cheap enough
392+ // that callers can call it in very tight loops, as very frequent calls ensure a
393+ // task wishing to yield when work is waiting will do so promptly. Checking the
394+ // runq of every P or calling netpoll are too expensive to do in every call, so
395+ // given intent is to bound how long work may wait, such checks only need to be
396+ // performed after some amount of time has elapsed (e.g. 0.25ms). To minimize
397+ // overhead when called at a higher frequency, this elapsed time is checked with
398+ // an exponential backoff.
399+ //
400+ // runqs are checked directly with non-atomic reads rather than runqempty: being
401+ // cheap is our top priority and a microsecond of staleness is fine as long as
402+ // the check does not get optimized out of a calling loop body (hence noinline).
403+ //
404+ //go:noinline
405+ func maybeYield () {
406+ gp := getg ()
407+
408+ // Don't park while locked to an OS thread.
409+ if gp .lockedm != 0 {
410+ return
411+ }
412+
413+ // If the local P's runq ring buffer/next is non-empty, yield to waiting G.
414+ if p := gp .m .p .ptr (); p .runqhead != p .runqtail || p .runnext != 0 {
415+ // If there is work in the local P's runq, we can yield by just going to the
416+ // back of the local P's runq via goyield: this achieves the same goal of
417+ // letting waiting work run instead of us, but without parking on the global
418+ // yieldq and potentially switching Ps. While that's our preferred choice,
419+ // we want to avoid thrashing back and forth between multiple Yield-calling
420+ // goroutines: in such a case it is better to just park one so the other
421+ // stops seeing it in the queue and yielding to it. To detect and break this
422+ // cycle, we put a 1 in the yieldchecks field: if the other goroutine yields
423+ // right back, but is then still in this runq bringing us here again, we'll
424+ // see this 1 and park instead. We can clobber yieldchecks here since we're
425+ // actively yielding -- we don't need the counter to decide to do so. And
426+ // our sentinel will in turn be clobbered the very next time the time is put
427+ // in the upper bits, which it will be when they're zero if we don't yield,
428+ // so this sentinel should be relatively reliable in indicating thrashing.
429+ if gp .yieldchecks == 1 {
430+ yieldPark ()
431+ return
432+ }
433+ gp .yieldchecks = 1
434+ // Go to the back of the local runq.
435+ goyield ()
436+ return
437+ }
438+
439+ // If the global runq is non-empty, park in the global yieldq right away: that
440+ // is work someone needs to pick up and it might as well be our P. We could,
441+ // potentially, directly claim it here and goyield or equivalently to try to
442+ // remain on this P, but just parking and letting this P go to findRunnable
443+ // avoid duplication of its logic and seems good enough.
444+ if ! sched .runq .empty () {
445+ yieldPark ()
446+ return
447+ }
448+
449+ // We didn't find anything via cheap O(1) checks of our runq or global runq but
450+ // it is possible there are goroutines waiting in runqs of other Ps that are
451+ // not being stolen by an idle P -- the lack of idle Ps (npidle=0) is what got
452+ // us here. Furthermore, given the lack of idle Ps, it is also possible that
453+ // ready conns are waiting for a netpoll to notice them and ready their
454+ // goroutines i.e. work to which we should then yield. However, searching all
455+ // runqs, and even more so netpoll, is too expensive for every maybeYield
456+ // call: being extremely low overhead is essential to allowing Yield() to be
457+ // called at high enough frequency to make the caller respond to changing load
458+ // promptly.
459+ //
460+ // Given our main goal here is to reduce/bound *how long* work waits, we can
461+ // do more extensive/expensive checks searching all runqs / netpoll less often
462+ // so long as we do them often enough. While we can't
463+ // define "enough" in term of a number of calls or probabilistic fraction of
464+ // calls (e.g. cheaprand()&1023==0) due to variability in caller frequency, we
465+ // can frame it in terms of elapsed time: so long as we check for waiting work
466+ // after some amount of time has elapsed, we bound how long it waits. We
467+ // choose approximately a quarter millisecond for this time: this is long
468+ // enough that it should make call overhead negligible, while still being a
469+ // duration smaller than the latency of any typical network requests.
470+ //
471+ // Checking nanotime() every call to implement this cap would in and of itself
472+ // be too expensive however, so we instead check the time with an exponential
473+ // backoff, using a simple call counter. We combine this counter and the last-
474+ // check time in uint32 field on G: 11 lower bits store the counter while the
475+ // 21 higher bits store the time as nanos quantized to a 0.25ms "epoch" by
476+ // discarding the lower 18 bits of a int64 nanotime() value. When the counter
477+ // 2^k - 1, we check the time; if the 'epoch' has changed (or if the counter is
478+ // about to overflow its 11 bits on next increment), we do the extended search
479+ // for waiting work. Note that while we discard 18 bits to quantize, since the
480+ // counter is in the low 11, we only shift by the difference and just mask the
481+ // rest out.
482+ const yieldCountBits , yieldCountMask = 11 , (1 << 11 ) - 1
483+ const yieldEpochShift = 18 - yieldCountBits
484+ gp .yieldchecks ++
485+ // Exp-backoff using 2^k-1 as when we check.
486+ if count := gp .yieldchecks & yieldCountMask ; (count & (count + 1 )) == 0 {
487+ prev := gp .yieldchecks &^ yieldCountMask
488+ now := uint32 (nanotime ()>> yieldEpochShift ) &^ yieldCountMask
489+ if now != prev || count == yieldCountMask {
490+ gp .yieldchecks = now
491+
492+ // Check runqs of all Ps; if we find anything park free this P to steal.
493+ for i := range allp {
494+ // We don't need the extra accuracy (and cost) of runqempty here either;
495+ // Worst-case we'll yield a check later or maybe park and unpark.
496+ if allp [i ].runqhead != allp [i ].runqtail || allp [i ].runnext != 0 {
497+ yieldPark ()
498+ return
499+ }
500+ }
501+
502+ // Check netpoll; a ready conn is basically a runnable goroutine which we
503+ // would yield to if we saw it, but the lack of idle Ps may mean nobody is
504+ // checking this as often right now and there may be ready conns waiting.
505+ if netpollinited () && netpollAnyWaiters () && sched .lastpoll .Load () != 0 {
506+ var found bool
507+ systemstack (func () {
508+ if list , delta := netpoll (0 ); ! list .empty () {
509+ injectglist (& list )
510+ netpollAdjustWaiters (delta )
511+ found = true
512+ }
513+ })
514+ if found {
515+ goyield ()
516+ }
517+ }
518+ }
519+ }
520+ }
521+
522+ // yieldPark parks the current goroutine in a waiting state with reason yield
523+ // and puts it in the yieldq queue for findRunnable. A goroutine that has to
524+ // park to Yield is considered "waiting" rather than "runnable" as it is blocked
525+ // in this state until there is strictly spare execution capacity available to
526+ // resume it, unlike runnable goroutines which generally take runs running at
527+ // regular intervals. A parked yielded goroutine is more like being blocked on
528+ // a cond var or lock that will be signaled when we next detect spare capacity.
529+ func yieldPark () {
530+ checkTimeouts ()
531+ gopark (yield_put , nil , waitReasonYield , traceBlockPreempted , 1 )
532+ }
533+
356534// goschedguarded yields the processor like gosched, but also checks
357535// for forbidden states and opts out of the yield in those cases.
358536//
@@ -3445,6 +3623,23 @@ top:
34453623 }
34463624 }
34473625
3626+ // Nothing runnable, so check for yielded goroutines parked in yieldq.
3627+ if ! sched .yieldq .empty () {
3628+ lock (& sched .lock )
3629+ bg := sched .yieldq .pop ()
3630+ unlock (& sched .lock )
3631+ if bg != nil {
3632+ trace := traceAcquire ()
3633+ casgstatus (bg , _Gwaiting , _Grunnable )
3634+ if trace .ok () {
3635+ // Match other ready paths for trace visibility.
3636+ trace .GoUnpark (bg , 0 )
3637+ traceRelease (trace )
3638+ }
3639+ return bg , false , false
3640+ }
3641+ }
3642+
34483643 // We have nothing to do.
34493644 //
34503645 // If we're in the GC mark phase, can safely scan and blacken objects,
@@ -3509,6 +3704,12 @@ top:
35093704 unlock (& sched .lock )
35103705 return gp , false , false
35113706 }
3707+
3708+ // Re-check yieldq again, this time while holding sched.lock.
3709+ if ! sched .yieldq .empty () {
3710+ unlock (& sched .lock )
3711+ goto top
3712+ }
35123713 if ! mp .spinning && sched .needspinning .Load () == 1 {
35133714 // See "Delicate dance" comment below.
35143715 mp .becomeSpinning ()
@@ -7111,6 +7312,20 @@ func (q *gQueue) popList() gList {
71117312 return stack
71127313}
71137314
7315+ // yield_put is the gopark unlock function for Yield. It enqueues the goroutine
7316+ // onto the global yield queue. Returning true keeps the G parked until another
7317+ // part of the scheduler makes it runnable again. The G remains in _Gwaiting
7318+ // after this returns. Nothing else will find/ready this G in the interim since
7319+ // it isn't on a runq until we put it on the yieldq for findRunnable to find.
7320+ //
7321+ //go:nosplit
7322+ func yield_put (gp * g , _ unsafe.Pointer ) bool {
7323+ lock (& sched .lock )
7324+ sched .yieldq .pushBack (gp )
7325+ unlock (& sched .lock )
7326+ return true
7327+ }
7328+
71147329// A gList is a list of Gs linked through g.schedlink. A G can only be
71157330// on one gQueue or gList at a time.
71167331type gList struct {
0 commit comments