Skip to content

Commit

Permalink
Merge pull request #1285 from michelle192837/queuefix
Browse files Browse the repository at this point in the history
Fix race on timer in util.queue.
  • Loading branch information
google-oss-prow[bot] authored Jul 9, 2024
2 parents 0e670bb + 09004a9 commit 1192f6a
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 3 deletions.
4 changes: 1 addition & 3 deletions util/queue/queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,12 +214,10 @@ func (q *Queue) sleep(d time.Duration) {
log.Debug("Sleeping...")
}
sleep := time.NewTimer(d)
defer sleep.Stop()
start := time.Now()
select {
case <-q.signal:
if !sleep.Stop() {
<-sleep.C
}
dur := time.Now().Sub(start)
log := log.WithField("after", dur.Round(time.Millisecond))
switch {
Expand Down
57 changes: 57 additions & 0 deletions util/queue/queue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -622,3 +622,60 @@ func TestPriorityQueue(t *testing.T) {
})
}
}

func TestSleep(t *testing.T) {
cases := []struct {
name string
sleep time.Duration
rouseAfter time.Duration // if specified, rouse after this time
wantRouse bool
}{
{
name: "basic",
sleep: 100 * time.Millisecond,
wantRouse: false,
},
{
name: "rouse during sleep",
sleep: 1 * time.Minute,
rouseAfter: 100 * time.Millisecond,
wantRouse: true,
},
{
name: "rouse after sleep",
sleep: 100 * time.Millisecond,
rouseAfter: 1 * time.Second,
wantRouse: false,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var q Queue
q.Init(logrus.WithField("name", tc.name), []string{"hi", "there"}, time.Now())

var slept, roused bool
var lock sync.Mutex
go func(rouseAfter time.Duration) {
if rouseAfter == 0 {
return
}
time.Sleep(rouseAfter)
q.rouse()
lock.Lock()
if !slept {
roused = true
}
lock.Unlock()
}(tc.rouseAfter)

q.sleep(tc.sleep)
lock.Lock()
slept = true
lock.Unlock()

if tc.wantRouse != roused {
t.Errorf("sleep() roused incorrectly (with sleep %q and rouse after %q): want rouse = %t, got %t", tc.sleep, tc.rouseAfter, tc.wantRouse, roused)
}
})
}
}

0 comments on commit 1192f6a

Please sign in to comment.