Skip to content

Commit 8151eba

Browse files
committed
Add SleepNotify, to notify a channel once the "waiter" is fully registered but before actually waiting for the Sleep to complete
1 parent 6d8d032 commit 8151eba

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

clockwork.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,15 @@ func (fc *FakeClock) After(d time.Duration) <-chan time.Time {
121121

122122
// Sleep blocks until the given duration has passed on the fakeClock.
123123
func (fc *FakeClock) Sleep(d time.Duration) {
124-
<-fc.After(d)
124+
fc.SleepNotify(d, make(chan struct{}))
125+
}
126+
127+
// SleepNotify blocks until the given duration has passed on the fakeClock.
128+
// Notify "ch" once the waiters has been updated
129+
func (fc *FakeClock) SleepNotify(d time.Duration, ch chan struct{}) {
130+
done := fc.After(d)
131+
close(ch)
132+
<-done
125133
}
126134

127135
// Now returns the current time of the fakeClock

clockwork_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package clockwork
33
import (
44
"context"
55
"errors"
6+
"math/rand"
7+
"sync/atomic"
68
"testing"
79
"time"
810
)
@@ -209,3 +211,26 @@ func TestFakeClockRace(t *testing.T) {
209211
go func() { fc.NewTimer(d) }()
210212
go func() { fc.Sleep(d) }()
211213
}
214+
215+
func TestSleepNotify(t *testing.T) {
216+
var calls atomic.Int32
217+
clock := NewFakeClock()
218+
beforeCh := make(chan struct{})
219+
afterCh := make(chan struct{})
220+
go func() { // thread #1
221+
clock.SleepNotify(time.Minute, beforeCh) // We want to wait for this before advancing the clock
222+
calls.Add(1)
223+
close(afterCh)
224+
}()
225+
go func() { // thread #2
226+
if rand.Intn(2) == 0 { // 50% chance of making another Sleep
227+
clock.Sleep(time.Hour)
228+
}
229+
}()
230+
<-beforeCh
231+
clock.Advance(time.Minute)
232+
<-afterCh
233+
if calls.Load() != 1 {
234+
t.Fatalf("SleepNotify() did not call the callback")
235+
}
236+
}

0 commit comments

Comments
 (0)