/
channels_test.go
112 lines (105 loc) · 1.92 KB
/
channels_test.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package concurrency
import (
"fmt"
"sync"
"testing"
)
func TestChannelIterateOverRange(t *testing.T) {
numbers := make(chan int)
go func(nums <-chan int) {
for n := range nums {
fmt.Println(printNumber(n))
}
}(numbers)
for i := 0; i < nums; i++ {
numbers <- i
}
close(numbers)
}
func TestChannelBuffered(t *testing.T) {
numbers := make(chan string, 5)
go func(nums <-chan string) {
for n := range nums {
fmt.Println(n)
}
}(numbers)
for i := 0; i < nums; i++ {
go func(c int) {
numbers <- printNumber(c)
}(i)
}
}
func TestChannelBufferedWithMultipleFunctions(t *testing.T) {
output := make(chan string)
go func() {
for out := range output {
fmt.Println(out)
}
}()
for _, c := range decimals {
go func(in string) {
num, err := numberConvert(in)
if err != nil {
output <- err.Error()
return
}
output <- printNumber(num)
}(c)
}
}
func TestMultipleChannelsSelect(t *testing.T) {
numbers := make(chan string)
greets := make(chan string)
done := make(chan bool)
finish := make(chan bool)
// reading all in the background, exiting when done
go func() {
for {
select {
case n := <-numbers:
fmt.Println(n)
case p := <-greets:
fmt.Println(p)
case <-finish:
return
}
}
}()
// sending numbers
go func() {
for i := 0; i < nums; i++ {
numbers <- printNumber(i)
}
done <- true
}()
// sending strings
go func() {
for _, person := range people {
greets <- sayHello(person)
}
done <- true
}()
// read to block until goroutines complete
<-done
<-done
// exit from first goroutine
finish <- true
}
func TestChannelRangeOnGoroutines(t *testing.T) {
var wg sync.WaitGroup
numbers := make(chan string)
go func(nums <-chan string) {
for n := range nums {
fmt.Println(n)
}
}(numbers)
for i := 0; i < nums; i++ {
wg.Add(1)
go func(c int) {
defer wg.Done()
numbers <- printNumber(c)
}(i)
}
wg.Wait()
close(numbers)
}