-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcurrency_pattern.go
116 lines (95 loc) · 1.61 KB
/
concurrency_pattern.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
113
114
115
116
package gopattern
import (
"fmt"
"io/ioutil"
"net/http"
"sync"
)
func numberGenerator(n int) <-chan int {
nState := make(chan int)
go func() {
for i := 1; i <= n; i = i + 1 {
nState <- i
}
defer close(nState)
}()
return nState
}
type bodyData struct {
Body []byte
Error error
}
func futureData(url string) <-chan bodyData {
pipe := make(chan bodyData, 1)
go func() {
var body []byte
var err error
resp, err := http.Get(url)
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
pipe <- bodyData{Body: body, Error: err}
}()
return pipe
}
func wgSchedule() {
var numArray []int
for i := 0; i <= 100; i = i + 1 {
numArray = append(numArray, i%10)
}
waitGroup := &sync.WaitGroup{}
printNum := func(wg *sync.WaitGroup, n int) {
print(n)
wg.Done()
}
for _, v := range numArray {
waitGroup.Add(1)
go printNum(waitGroup, v)
if v%9 == 0 && v != 0 {
waitGroup.Wait()
println()
}
}
}
func onceDo(n int) {
var justOne int
var once sync.Once
wg := &sync.WaitGroup{}
increaseCount := func() {
justOne++
print("set one")
}
doOne := func() {
once.Do(increaseCount)
println(justOne)
defer wg.Done()
}
wg.Add(n + 1)
for i := 0; i <= n; i++ {
go doOne()
}
wg.Wait()
}
func selectCase() {
nState := numberGenerator(100)
lock := &sync.Mutex{}
for {
select {
case num := <-nState:
lock.Lock()
print(num)
case num := <-nState:
fmt.Printf("%d print line 2", num)
}
}
}
func bufferedChannel() <-chan int {
c := make(chan int, 3)
c <- 1
c <- 2
return c
}
func unbufferedChannel() <-chan int {
c := make(chan int)
c <- 1
return c
}