Golang 超时不与通道一起执行
Golang timeout is not executed with channels
我正在使用 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()
}
你的超时不会发生,因为你的一个 goroutine 每隔 1.5 秒(左右)重复在你的 c1
通道上发送一个值,并且你的超时只会在没有价值的情况下发生从 c1
收到 2 秒。
一旦从 c1
收到值,在下一次迭代中再次执行 select
将进行 new time.After()
调用其中 returns 一个 new 通道,只有在 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
...
我正在使用 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()
}
你的超时不会发生,因为你的一个 goroutine 每隔 1.5 秒(左右)重复在你的 c1
通道上发送一个值,并且你的超时只会在没有价值的情况下发生从 c1
收到 2 秒。
一旦从 c1
收到值,在下一次迭代中再次执行 select
将进行 new time.After()
调用其中 returns 一个 new 通道,只有在 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
...