Go实现最简单的超时控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import (
"fmt"
"time"
)

func main() {
ch := make(chan int)

go func(ch chan int) {
time.Sleep(time.Second * 10)
ch <- 1
}(ch)

select {
case <-ch:
fmt.Println("ok")
case <-time.After(time.Second * 5):
fmt.Println("time out")
}
}