-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
112 lines (100 loc) · 1.73 KB
/
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
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 fizzbuzzmultithreaded
import (
"fmt"
"sync"
)
var (
wg = sync.WaitGroup{}
)
// 時間複雜 O(), 空間複雜 O()
func FizzBuzz(n int) {
fb := NewFizzBuzz()
wg.Add(4)
go fb.fizz()
go fb.buzz()
go fb.fizzbuzz()
go fb.number()
for i := 1; i <= n; i++ {
if i%3 == 0 && i%5 == 0 {
fb.fizzbuzzCh <- struct{}{}
} else if i%3 == 0 {
fb.fizzCh <- struct{}{}
} else if i%5 == 0 {
fb.buzzCh <- struct{}{}
} else {
fb.numberCh <- i
}
<-fb.orderCh
}
fb.done <- struct{}{}
fb.done <- struct{}{}
fb.done <- struct{}{}
fb.done <- struct{}{}
wg.Wait()
}
type FizzBuzzStruct struct {
numberCh chan int
fizzCh chan struct{}
buzzCh chan struct{}
fizzbuzzCh chan struct{}
orderCh chan struct{}
done chan struct{}
}
func NewFizzBuzz() *FizzBuzzStruct {
return &FizzBuzzStruct{
numberCh: make(chan int),
fizzCh: make(chan struct{}),
buzzCh: make(chan struct{}),
fizzbuzzCh: make(chan struct{}),
orderCh: make(chan struct{}),
done: make(chan struct{}, 4),
}
}
func (fb *FizzBuzzStruct) fizz() {
defer wg.Done()
for {
select {
case <-fb.fizzCh:
fmt.Print("fizz")
fb.orderCh <- struct{}{}
case <-fb.done:
return
}
}
}
func (fb *FizzBuzzStruct) buzz() {
defer wg.Done()
for {
select {
case <-fb.buzzCh:
fmt.Print("buzz")
fb.orderCh <- struct{}{}
case <-fb.done:
return
}
}
}
func (fb *FizzBuzzStruct) fizzbuzz() {
defer wg.Done()
for {
select {
case <-fb.fizzbuzzCh:
fmt.Print("fizzbuzz")
fb.orderCh <- struct{}{}
case <-fb.done:
return
}
}
}
func (fb *FizzBuzzStruct) number() {
defer wg.Done()
for {
select {
case v := <-fb.numberCh:
fmt.Print(v)
fb.orderCh <- struct{}{}
case <-fb.done:
return
}
}
}