2

我正在使用 goroutines/channels。这是我的代码。为什么超时情况没有得到执行?

func main() {
    c1 := make(chan int, 1)

    go func() {
        for {
            time.Sleep(1500 * time.Millisecond)
            c1 <- 10
        }
    }()

    go func() {
        for {
            select {
            case i := <-c1:
                fmt.Println(i)
            case <-time.After(2000 * time.Millisecond):
                fmt.Println("TIMEOUT") // <-- Not Executed
            }
        }
    }()

    fmt.Scanln()
}
4

1 回答 1

3

您的超时不会发生,因为您的一个 goroutine 每隔 1.5 秒(左右)在您的频道上重复发送一个值,并且只有在 2 秒内c1没有收到任何值时才会发生超时。c1

一旦从 接收到一个值c1,在下一次迭代中select再次执行一个 time.After()的调用,它将返回一个的通道,一个值只会在另外 2 秒后发送。上一次执行的超时通道select被丢弃,不再使用。

要在 2 秒后接收超时,只需创建一次超时通道,例如:

timeout := time.After(2000 * time.Millisecond)
for {
    select {
    case i := <-c1:
        fmt.Println(i)
    case <-timeout:
        fmt.Println("TIMEOUT") // Will get executed after 2 sec
    }
}

输出:

10
TIMEOUT
10
10
10
...
于 2016-01-20T08:35:29.080 回答