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

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

如何在 Golang 中使用“time.After”和“default”?

如何在 Golang 中使用“time.After”和“default”?

Go
UYOU 2022-03-07 15:52:39
我正在嘗試理解 Golang 例程的簡單代碼:package mainimport (    "fmt"    "time")func sleep(seconds int, endSignal chan<- bool) {    time.Sleep(time.Duration(seconds) * time.Second)    endSignal <- true}func main() {    endSignal := make(chan bool, 1)    go sleep(3, endSignal)    var end bool    for !end {        select {        case end = <-endSignal:            fmt.Println("The end!")        case <-time.After(5 * time.Second):            fmt.Println("There's no more time to this. Exiting!")            end = true        }    }}很好,但是為什么我不能在這個“選擇”塊中使用簡單的默認值?像這樣的東西:for !end {    select {    case end = <-endSignal:        fmt.Println("The end.")    case <-time.After(4 * time.Second):        fmt.Println("There's no more time to this. Exiting!")        end = true    default:        fmt.Println("No end signal received.")    }}它得到這個輸出:? go run goroutines-timeout.goNo end signal received!No end signal received!No end signal received!No end signal received!...The end!我不明白為什么。
查看完整描述

1 回答

?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

每次執行時,time.After(4 * time.Second)您都會創建一個新的計時器通道。該select語句無法記住它在上一次迭代中選擇的通道。您還采用了異步操作并將其變成了一個繁忙的循環,從而違背了select語句的目的。


您所需要的只是圍繞您感興趣的兩個頻道進行簡單的選擇。它根本不需要循環。


select {

case <-endSignal:

    fmt.Println("The end!")

case <-time.After(4 * time.Second):

    fmt.Println("There's no more time to this. Exiting!")

}

https://play.golang.org/p/jb4EE8e6cw


如果您真的想多次輪詢,請將計時器設置在 for 循環之外,以便每次迭代都檢查相同的計時器


timeout := time.After(5 * time.Second)

pollInt := time.Second


for {

    select {

    case <-endSignal:

        fmt.Println("The end!")

        return

    case <-timeout:

        fmt.Println("There's no more time to this. Exiting!")

        return

    default:

        fmt.Println("still waiting")

    }

    time.Sleep(pollInt)

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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