-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeout.go
56 lines (48 loc) · 1.25 KB
/
timeout.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import "time"
import "fmt"
/*
Timeouts are important for programs that connect to external resources or that otherwise need
to bound execution time. Implementing timeouts in Go is easy and elegant thanks to channels and select.
*/
func main() {
outOfTime()
inTime()
}
func outOfTime() {
// For our example, suppose we’re executing an external call that returns its result on a
// channel c1 after 2s.
c1 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c1 <- "result 1"
}()
/*
Here’s the select implementing a timeout.
res := <-c1 awaits the result
<-Time.After awaits a value to be sent after the timeout of 1s.
Since select proceeds with the first receive that’s ready, we’ll take the timeout case if
the operation takes more than the allowed 1s.
*/
select {
case res := <-c1:
fmt.Println(res)
case <-time.After(1 * time.Second):
fmt.Println("timeout 1")
}
}
func inTime() {
c2 := make(chan string, 1)
go func() {
time.Sleep(2 * time.Second)
c2 <- "result 2"
}()
// If we allow a longer timeout of 3s, then the receive from c2 will succeed and we’ll
// print the result.
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(3 * time.Second):
fmt.Println("timeout 2")
}
}