Skip to content

Commit

Permalink
Fix stop before start and add test
Browse files Browse the repository at this point in the history
  • Loading branch information
PlasmaPower committed Dec 3, 2024
1 parent 1403c88 commit 9983043
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions util/stopwaiter/stopwaiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,14 @@ func getAllStackTraces() string {

func (s *StopWaiterSafe) stopAndWaitImpl(warningTimeout time.Duration) error {
s.StopOnly()
if !s.Started() {
// No need to wait, because nothing can be started if it's already stopped.
return nil
}
// Even if StopOnly has been previously called, make sure we wait for everything to shut down.
// Otherwise, a StopOnly call followed by StopAndWait might return early without waiting.
// At this point started must be true (because it was true above and cannot go back to false),
// so GetWaitChannel won't return an error.
waitChan, err := s.GetWaitChannel()
if err != nil {
return err
Expand Down
17 changes: 17 additions & 0 deletions util/stopwaiter/stopwaiter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package stopwaiter

import (
"context"
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -73,3 +74,19 @@ func TestStopWaiterStopAndWaitMultipleTimes(t *testing.T) {
sw.StopAndWait()
sw.StopAndWait()
}

func TestStopWaiterStopOnlyThenStopAndWait(t *testing.T) {
t.Parallel()
sw := StopWaiter{}
sw.Start(context.Background(), &TestStruct{})
var threadStopping atomic.Bool
sw.LaunchThread(func(context.Context) {
time.Sleep(time.Second)
threadStopping.Store(true)
})
sw.StopOnly()
sw.StopAndWait()
if !threadStopping.Load() {
t.Error("StopAndWait returned before background thread stopped")
}
}

0 comments on commit 9983043

Please sign in to comment.