Skip to content
This repository has been archived by the owner on May 18, 2023. It is now read-only.

Commit

Permalink
Merge pull request #45 from smirnov-vs/fix/afterfunc_goroutine
Browse files Browse the repository at this point in the history
AfterFunc underlying function is executed in its own goroutine
  • Loading branch information
djmitche committed Apr 23, 2023
2 parents 023ccf9 + e225bc7 commit c7aedc1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
4 changes: 2 additions & 2 deletions clock.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ func (m *Mock) After(d time.Duration) <-chan time.Time {
return m.Timer(d).C
}

// AfterFunc waits for the duration to elapse and then executes a function.
// AfterFunc waits for the duration to elapse and then executes a function in its own goroutine.
// A Timer is returned that can be stopped.
func (m *Mock) AfterFunc(d time.Duration, f func()) *Timer {
m.mu.Lock()
Expand Down Expand Up @@ -321,7 +321,7 @@ func (t *internalTimer) Tick(now time.Time) {
t.mock.mu.Lock()
if t.fn != nil {
// defer function execution until the lock is released, and
defer t.fn()
defer func() { go t.fn() }()
} else {
t.c <- now
}
Expand Down
19 changes: 10 additions & 9 deletions clock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -604,24 +604,25 @@ func ExampleMock_After() {
func ExampleMock_AfterFunc() {
// Create a new mock clock.
clock := NewMock()
count := 0
var count counter
count.incr()

// Execute a function after 10 mock seconds.
clock.AfterFunc(10*time.Second, func() {
count = 100
count.incr()
})
gosched()

// Print the starting value.
fmt.Printf("%s: %d\n", clock.Now().UTC(), count)
fmt.Printf("%s: %d\n", clock.Now().UTC(), count.get())

// Move the clock forward 10 seconds and print the new value.
clock.Add(10 * time.Second)
fmt.Printf("%s: %d\n", clock.Now().UTC(), count)
fmt.Printf("%s: %d\n", clock.Now().UTC(), count.get())

// Output:
// 1970-01-01 00:00:00 +0000 UTC: 0
// 1970-01-01 00:00:10 +0000 UTC: 100
// 1970-01-01 00:00:00 +0000 UTC: 1
// 1970-01-01 00:00:10 +0000 UTC: 2
}

func ExampleMock_Sleep() {
Expand Down Expand Up @@ -725,9 +726,9 @@ func TestMock_AddAfterFuncRace(t *testing.T) {

mockedClock := NewMock()

called := false
var calls counter
defer func() {
if !called {
if calls.get() == 0 {
t.Errorf("AfterFunc did not call the function")
}
}()
Expand All @@ -738,7 +739,7 @@ func TestMock_AddAfterFuncRace(t *testing.T) {
<-start

mockedClock.AfterFunc(time.Millisecond, func() {
called = true
calls.incr()
})
}()

Expand Down

0 comments on commit c7aedc1

Please sign in to comment.