runtime: optimization to reduce P churn #32113
The following is a fairly frequent pattern that appears in our code and others:
The scheduler exhibits two different behaviors, depending on whether goroutine2 is busy and there are available Ps.
In the second case, if the P wakes and successfully steals the now runnable goroutine2, i.e. (3) happens first, then it will start executing on the new P. Unfortunately, the whole dance will happen again with the result. If the P wakes but does not successfully steal the now runnable goroutine2, i.e. (4) happens first and goroutine2 is run locally, then a large number of cycles are wasted. Either way, this dance happens again with the result. In both cases, we spend a large number of cycles and interprocessor co-ordination costs for what should be a goroutine context switch.
These are further problems caused by this, as it will introduce unnecessary work stealing and bouncing of goroutines between system threads and cores. (Leading to locality inefficiencies.)
With an oracle, the ideal schedule after (1) would be:
In essence, we want to yield the goroutine1's time to goroutine2 in this case, or at least avoid all the wasted signaling overhead. To put it another way: if goroutine1's P will block, then it fills the role of the "idle P" far more efficiently.
It may be possible to specifically optimize for this case in the compiler, just as certain loop patterns are optimized.
In the case where a blocking channel send is immediately followed by a blocking channel receive, I propose an optimization that tries to avoid these scheduler round trips.
Here's a rough sketch of the idea:
I thought about this problem a few years ago when it caused issues. In the past, I considered the possibility of a different channel operator. Something like:
ch1 <~ data
This operator would write to the channel and immediately yield to the other goroutine, if it was not already running (otherwise would fall back to the existing channel behavior). Using this operator in the above situation would make it much more efficient in general.
However, this is a language change, and confusing to users. When do you use which operator? It would be good to have the effect of this optimization out of the box.
The text was updated successfully, but these errors were encountered:
What about just enforcing a minimum delay between when a G is created and when it can be stolen? That gives the local P time to finish the spawning G (finish = either done or block) and pick up the new G itself.
The delay would be on the order of the overhead to move a G between processors (sys calls, cache warmup, etc.)
The tricky part is to not even wake the remote P when the goroutine is queued. We want a timer somehow that can be cancelled if the G is started locally.
Yes, most of the waste is generated by the wakeup call itself. Ensuring that the other P does not steal the G is probably a minor improvement, but you're still going to waste a ton of cycles (maybe even doing these wake ups twice -- on (1) and (4)).
I think using a timer gets much trickier. This is the reason I have limited the proposal to compiler-identified sequences of "chansend(block=true); chanrecv(block=true)" calls. It's possible that the system thread could be pre-empted between those calls, but if the system is busy (though Ps in this process may still be idle) it's probably even more valuable to not waste useless cycles.
This has come up repeatedly. Obviously it is easy to recognize and fuse
It's harder to see that in more complex code that would benefit from the optimization, though. We've fiddled with heuristics in the runtime to try to wait a little bit before stealing a G from a P, and so on. Probably more tuning is needed.
It's unclear this needs to be a proposal, unless you are proposing a language change, and it sounds like you've backed away from that.
The way forward with a suggestion like this is to try implementing it and see how much of an improvement (and how general of an improvement) it yields.
I backed away from a language change proposal based on the assumption that it would likely not be accepted. My personal preference would be to have an operation like <~ that immediately switches to the other goroutine if currently waiting. (And behaves like a normal channel operation if busy.) But I realize that the existence of this operator might be confusing.
I think it's unclear how much of a impact this would have in general. This is probably just be a tiny optimization that doesn't matter in the general case, but can help in a few very specific ones. For us, it might let us structure some goroutine interactions much more efficiently.
I hacked something together, and it seems like there's a decent effect on microbenchmarks at least (unless I screwed something up).
The system time is telling @ 20x, and the extra 14% in CPU usage is indicative of an additional P waking up with nothing to do. (Or maybe it occasionally successfully steals the goroutine, which is also bad.)
Assuming this small optimization is readily acceptable -- what's the best way to group those operations and transform the channel calls? The runtime bits are straight-forward, but any up front guidance on the compiler side is appreciated. Otherwise, I'm just planning to call a specialized scan in walkstmt list, but maybe there's a better way.
I've started looking into this. I've got a very naive implementation (probably very similar to Adin's) to use with his microbenchmark.
Fixed time (
Fixed iterations (
I've included both since the the different fixed dimensions change the interpretation. e.g., the first case has higher cycles after because it is simply able to do a lot more work. And it still does nearly double the iterations in 30% less CPU time (== far less time stalled)!
This certainly looks worthwhile from the micro-benchmark perspective. The questions remaining to me are if we can efficiently and reliably detect these scenarios, and if they affect many programs.
Neither @amscanne nor my prototype change any language syntax or APIs. Rather, the compiler detects channel send followed immediately by channel receive and rather than calling the typical
Both prototypes are rudimentary and would probably hurt performance for many programs due to poor decisions and would need more refinement.
Some synchronization patterns require the ability to simultaneously wake and sleep a goroutine. For the sleep package, this is the case when a waker must be asserted when a subsequent fetch is imminent. Currently, this operation results in significant P churn in the runtime, which ping-pongs execution between multiple system threads and cores and consumes a significant amount of host CPU (and because of the context switches, this can be significant worse with mitigations for side channel vulnerabilities). The solution is to introduce a dedicated mechanism for a synchronous switch which does not wake another runtime P (see golang/go#32113). This can be used by the `AssertAndFetch` API in the sleep package. The benchmark results for this package are very similiar to raw channel operations for all cases, with the exception of operations that do not wait. The primary advantage is more precise control over scheduling. This will be used in a subsequent change. ``` BenchmarkGoAssertNonWaiting BenchmarkGoAssertNonWaiting-8 261364384 4.976 ns/op BenchmarkGoSingleSelect BenchmarkGoSingleSelect-8 20946358 57.77 ns/op BenchmarkGoMultiSelect BenchmarkGoMultiSelect-8 6071697 197.0 ns/op BenchmarkGoWaitOnSingleSelect BenchmarkGoWaitOnSingleSelect-8 4978051 235.4 ns/op BenchmarkGoWaitOnMultiSelect BenchmarkGoWaitOnMultiSelect-8 2309224 520.2 ns/op BenchmarkSleeperAssertNonWaiting BenchmarkSleeperAssertNonWaiting-8 447325033 2.657 ns/op BenchmarkSleeperSingleSelect BenchmarkSleeperSingleSelect-8 21488844 55.19 ns/op BenchmarkSleeperMultiSelect BenchmarkSleeperMultiSelect-8 21851674 54.89 ns/op BenchmarkSleeperWaitOnSingleSelect BenchmarkSleeperWaitOnSingleSelect-8 2860327 416.4 ns/op BenchmarkSleeperWaitOnSingleSelectSync BenchmarkSleeperWaitOnSingleSelectSync-8 2741733 427.1 ns/op BenchmarkSleeperWaitOnMultiSelect BenchmarkSleeperWaitOnMultiSelect-8 2867484 418.1 ns/op BenchmarkSleeperWaitOnMultiSelectSync BenchmarkSleeperWaitOnMultiSelectSync-8 2789158 427.9 ns/op ``` PiperOrigin-RevId: 406873844
Background: Scheduler is very easy to get into a "P churn" problem as stated by Adin in golang#32113. This problem is more serious in gVisor as futex() syscall, used for wake and idle M, is a much heavier operation from GR0 into HR0. Adin proposed to add the context semantics into scheduler to decide if we need to wake a new M. Let's call it a local strategy. Here we propose another way to solve this problem. Let's call it a global strategy. When we need to decide whether to start a new M, except the condition of an extra P, let's calculate # of runnable Gs and # of running Ps. When # of runnable Gs <= # of running Ps * factor, do not start another M, as those already-running Ms will steal Gs this P. We have tried using a factor of 1.5; but then switch to 1. The mechnism applies when we ready a G; and we also add this to handleoffp(). For handoffp(), the previous strategy to wake up a M is to satisfy one of below two conditions: - the local runq is not empty; - the global runq is not empty. We constrain the 2nd condition by checking the comparison of # of running Gs and # of running Ps. (Note that the running P here has different meaning with the one used above for wakep(). Two concerns are raised for this method: - If it adds too much contention when we do the G/P counting? A side info is that we usually set GOMAXPROCS to 4 or 8. And as we see from our result, CPU util is much lower; and we don't see too much contention in the flame graph. - If it brings worse latency? Yes, it does incur small regression in latency, but the CPU util seems a big enough advantage. Signed-off-by: Shi Liu <email@example.com> Signed-off-by: Jielong Zhou <firstname.lastname@example.org> Signed-off-by: Yong He <email@example.com> Signed-off-by: Jianfeng Tan <firstname.lastname@example.org>