File tree Expand file tree Collapse file tree 2 files changed +34
-1
lines changed
Expand file tree Collapse file tree 2 files changed +34
-1
lines changed Original file line number Diff line number Diff 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.
123123func (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
Original file line number Diff line number Diff line change @@ -3,6 +3,8 @@ package clockwork
33import (
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+ }
You can’t perform that action at this time.
0 commit comments