forked from lotusirous/go-concurrency-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
36 lines (31 loc) · 712 Bytes
/
main.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
package main
import (
"fmt"
"math/rand"
"time"
)
// the boring function return a channel to communicate with it.
func boring(msg string) <-chan string { // <-chan string means receives-only channel of string.
c := make(chan string)
go func() { // we launch goroutine inside a function.
for i := 0; ; i++ {
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond)
}
}()
return c // return a channel to caller.
}
func main() {
c := boring("Joe")
// timeout for the whole conversation
timeout := time.After(5 * time.Second)
for {
select {
case s := <-c:
fmt.Println(s)
case <-timeout:
fmt.Println("You talk too much.")
return
}
}
}