Skip to content

Commit

Permalink
cpu: fix ticker to avoid close early (#40036)
Browse files Browse the repository at this point in the history
ref #40029
  • Loading branch information
hawkingrei authored Dec 21, 2022
1 parent fdf335e commit ae2d551
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
1 change: 1 addition & 0 deletions util/cpu/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@ go_test(
name = "cpu_test",
srcs = ["cpu_test.go"],
embed = [":cpu"],
flaky = True,
deps = ["@com_github_stretchr_testify//require"],
)
8 changes: 5 additions & 3 deletions util/cpu/cpu.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,13 @@ func NewCPUObserver() *Observer {

// Start starts the cpu observer.
func (c *Observer) Start() {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
c.wg.Add(1)
go func() {
defer c.wg.Done()
ticker := time.NewTicker(100 * time.Millisecond)
defer func() {
ticker.Stop()
c.wg.Done()
}()
for {
select {
case <-ticker.C:
Expand Down
7 changes: 4 additions & 3 deletions util/cpu/cpu_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@ func TestCPUValue(t *testing.T) {
}
}()
}
time.Sleep(30 * time.Second)
require.Greater(t, Observer.observe(), 0.0)
require.Less(t, Observer.observe(), 1.0)
Observer.Start()
time.Sleep(5 * time.Second)
require.GreaterOrEqual(t, GetCPUUsage(), 0.0)
require.Less(t, GetCPUUsage(), 1.0)
Observer.Stop()
close(exit)
wg.Wait()
Expand Down

0 comments on commit ae2d551

Please sign in to comment.