Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cpu: fix ticker to avoid close early #40036

Merged
merged 12 commits into from
Dec 21, 2022
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