1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func TestSelectTimeLimiter(t *testing.T) {
var res string

done := make(chan struct{}, 1)

go func() {
time.Sleep(500 * time.Millisecond)
res = "ok"
done <- struct{}{}
}()

select {
case <-done:
case <-time.After(300 * time.Millisecond):
res = "time out"
    //default: default 的出现会导致永远无法进入第二个 case
// println("default")
}

println(res)
}

知识点:time.After 方法返回一个 chan

1
2
3
4
5
6
7
8
9
// After waits for the duration to elapse and then sends the current time
// on the returned channel.
// It is equivalent to NewTimer(d).C.
// The underlying Timer is not recovered by the garbage collector
// until the timer fires. If efficiency is a concern, use NewTimer
// instead and call Timer.Stop if the timer is no longer needed.
func After(d Duration) <-chan Time {
return NewTimer(d).C
}