亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

帶有 Ticker 的 Goroutine 選擇循環導致 CPU 達到 100%

帶有 Ticker 的 Goroutine 選擇循環導致 CPU 達到 100%

Go
開滿天機 2022-06-27 17:10:10
我有這個循環,它的作用是嘗試反復輪詢另一臺服務器。我使用ticker來實現這一點,但是程序反復顯示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 中使用 ticker 以使其不會消耗 100% CPU,我錯過了什么?
查看完整描述

1 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

你的循環中select有一個default分支。如果其他cases 都沒有準備好繼續,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

        }

    }

}


查看完整回答
反對 回復 2022-06-27
  • 1 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號