Skip to content

Commit 72ccabc

Browse files
prattmicianlancetaylor
authored andcommitted
[release-branch.go1.15] runtime, time: disable preemption in addtimer
The timerpMask optimization updates a mask of Ps (potentially) containing timers in pidleget / pidleput. For correctness, it depends on the assumption that new timers can only be added to a P's own heap. addtimer violates this assumption if it is preempted after computing pp. That G may then run on a different P, but adding a timer to the original P's heap. Avoid this by disabling preemption while pp is in use. Other uses of doaddtimer should be OK: * moveTimers: always moves to the current P's heap * modtimer, cleantimers, addAdjustedTimers, runtimer: does not add net new timers to the heap while locked For #44868 Fixes #45731 Change-Id: I4a5d080865e854931d0a3a09a51ca36879101d72 Reviewed-on: https://go-review.googlesource.com/c/go/+/300610 Trust: Michael Pratt <[email protected]> Run-TryBot: Michael Pratt <[email protected]> Reviewed-by: Michael Knyszek <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> TryBot-Result: Go Bot <[email protected]> Reviewed-on: https://go-review.googlesource.com/c/go/+/313129 Trust: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> Reviewed-by: Michael Pratt <[email protected]>
1 parent 5aed4ce commit 72ccabc

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/runtime/time.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,13 +254,18 @@ func addtimer(t *timer) {
254254

255255
when := t.when
256256

257+
// Disable preemption while using pp to avoid changing another P's heap.
258+
mp := acquirem()
259+
257260
pp := getg().m.p.ptr()
258261
lock(&pp.timersLock)
259262
cleantimers(pp)
260263
doaddtimer(pp, t)
261264
unlock(&pp.timersLock)
262265

263266
wakeNetPoller(when)
267+
268+
releasem(mp)
264269
}
265270

266271
// doaddtimer adds t to the current P's heap.

src/time/sleep_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -501,3 +501,19 @@ func TestZeroTimerStopPanics(t *testing.T) {
501501
var tr Timer
502502
tr.Stop()
503503
}
504+
505+
// Test that zero duration timers aren't missed by the scheduler. Regression test for issue 44868.
506+
func TestZeroTimer(t *testing.T) {
507+
if testing.Short() {
508+
t.Skip("-short")
509+
}
510+
511+
for i := 0; i < 1000000; i++ {
512+
s := Now()
513+
ti := NewTimer(0)
514+
<-ti.C
515+
if diff := Since(s); diff > 2*Second {
516+
t.Errorf("Expected time to get value from Timer channel in less than 2 sec, took %v", diff)
517+
}
518+
}
519+
}

0 commit comments

Comments
 (0)