问题描述
我有一个循环,它试图重复轮询到另一台服务器。我使用代码来实现此目的,但是程序反复显示100%的cpu使用率。
此行情收录器在goroutine中运行。 HTTP服务器在另一个goroutine中运行。
func() Monitor() {
abort := make(chan bool)
log.Info("Monitor started.")
// start the monitor goroutine
go func() {
defer log.Info("Stopped monitor")
ticker := time.NewTicker(time.Duration(35.0) * time.Second)
defer ticker.Stop()
log.Info("Monitor started! \n")
for {
select {
case t := <-ticker.C:
log.Infof("Subscribe to service at time %v\n",t)
if err := selfConn.SubscribetoService(); err != nil {
log.Errorf("Failed to subscribe to primary connector: %v",err)
}
case <-abort:
log.Info("Finished routine!")
return
default:
continue
}
}
}()
go func() {
time.Sleep(10 * time.Minute)
abort <- true
}()
}
但是,当监视器循环开始时,并且每次发送到股票行情通道的信号时,cpu都会始终显示100%。
我错过了在goroutine中使用代码来使它不会消耗100%的cpu的什么功能?
解决方法
您的循环中有一个select
和一个default
分支。如果其他case
中没有一个准备好进行,则default
分支将立即执行,因此您的下一次迭代将立即开始,而无需等待。这是一个繁忙的循环。
此外,无需终止其他goroutine,您可以在同一goroutine中使用计时器。
例如:
func monitor() {
log.Info("Monitor started.")
ticker := time.NewTicker(35 * time.Second)
defer ticker.Stop()
timeoutCh := time.After(10 * time.Minute)
for {
select {
case t := <-ticker.C:
log.Infof("Subscribe to service at time %v\n",t)
if err := selfConn.SubscribeToService(); err != nil {
log.Errorf("Failed to subscribe to primary connector: %v",err)
}
case <-timeoutCh:
log.Info("Finished routine!")
return
}
}
}