select 与 time.After 配合使用的问题

今天在工作中发现了一个有趣的现象。

在一个select中设定了两个定时器,本来预计哪个定时器到达就运行相应指令的,但是发现最终只有时间最短的定时器一直得到执行,其它定时器完全没有得到执行。

复制代码
package main

import (
"fmt"
"time"
)

func main(){
    for i:=0; i< 3;i ++ {
        select{
            case <-time.After(7*time.Second):
                fmt.Println("1 second")
                
            case <-time.After(5*time.Second):
                fmt.Println("8 seconds")
        }
    }
}
复制代码

服务器输出是:

8 seconds
8 seconds
8 seconds

在stackoverflow上有人提到了,time.After每次都会返回一个新的channel,所以select不可能监测到新产生的channel:
https://stackoverflow.com/questions/39212333/how-can-i-use-time-after-and-default-in-golang
复制代码
package main

import (
"fmt"
"time"
)

func main(){
    count := 0
    timeout1 := time.After(7*time.Second)
    timeout2 := time.After(5*time.Second)
    for i:=0; i< 36; i++{
        select{
            case <-timeout1:
                fmt.Println(count, "7 second")
                
            case <-timeout2:
                fmt.Println(count, "5 seconds")
                
            default:
                fmt.Println(count, "Just wait")
                
        }
        count++
        time.Sleep(1*time.Second)
    }
}
复制代码
0 Just wait
1 Just wait
2 Just wait
3 Just wait
4 Just wait
5 5 seconds
6 Just wait
7 7 second
8 Just wait
9 Just wait
10 Just wait
11 Just wait
12 Just wait
13 Just wait
14 Just wait
15 Just wait
16 Just wait
17 Just wait
18 Just wait
19 Just wait
20 Just wait
21 Just wait
22 Just wait
23 Just wait
24 Just wait
25 Just wait
26 Just wait
27 Just wait
28 Just wait
29 Just wait
30 Just wait
31 Just wait
32 Just wait
33 Just wait
34 Just wait
35 Just wait
 
posted @   elar  阅读(417)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示