neo*_*ang 3 timeout channel go
我正在使用 goroutine/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()
}
Run Code Online (Sandbox Code Playgroud)
你的超时不会发生,因为你的一个 goroutine 每隔 1.5 秒(左右)就会在你的通道上重复发送一个值,并且只有在 2 秒内c1没有收到任何值的情况下才会发生超时。c1
一旦从 接收到值,在再次c1执行的下一次迭代中,将进行新的调用,该调用返回一个新通道,仅在另外 2 秒后才在该通道上发送值。之前的超时通道select time.After()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
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
10
TIMEOUT
10
10
10
...
Run Code Online (Sandbox Code Playgroud)