-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeout.go
42 lines (37 loc) · 860 Bytes
/
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
// Go Concurrency Pattern: Timeout
//
package main
import (
"fmt"
"math/rand"
"time"
)
func demoWorker() <-chan int {
cost := make(chan int)
go func() {
// sleep rand 2 ~ 6 seconds as if it is working
t := 2 + rand.Int() % 5
time.Sleep(time.Duration(t) * time.Second)
cost <- t
}()
return cost
}
func timeoutWorker(n int) <-chan struct{} {
timeout := make(chan struct{})
go func() {
// sleep n seconds for timeout
time.Sleep(time.Duration(n) * time.Second)
timeout <- struct{}{}
}()
return timeout
}
func main() {
rand.Seed(time.Now().Unix())
n := 5
select {
case cost := <-demoWorker():
fmt.Printf("Work Complete, cost: %d seconds\n", cost)
case <-timeoutWorker(n):
fmt.Printf("Timeout after %d seconds\n", n)
}
}