@@ -118,6 +118,118 @@ Constraints:
118
118
https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/1195.Fizz-Buzz-Multithreaded/main.go
119
119
120
120
``` go
121
+ package fizzbuzzmultithreaded
122
+
123
+ import (
124
+ " fmt"
125
+ " sync"
126
+ )
127
+
128
+ var (
129
+ wg = sync.WaitGroup {}
130
+ )
131
+
132
+ // 時間複雜 O(), 空間複雜 O()
133
+ func FizzBuzz (n int ) {
134
+ fb := NewFizzBuzz ()
135
+
136
+ wg.Add (4 )
137
+
138
+ go fb.fizz ()
139
+ go fb.buzz ()
140
+ go fb.fizzbuzz ()
141
+ go fb.number ()
142
+
143
+ for i := 1 ; i <= n; i++ {
144
+ if i%3 == 0 && i%5 == 0 {
145
+ fb.fizzbuzzCh <- struct {}{}
146
+ } else if i%3 == 0 {
147
+ fb.fizzCh <- struct {}{}
148
+ } else if i%5 == 0 {
149
+ fb.buzzCh <- struct {}{}
150
+ } else {
151
+ fb.numberCh <- i
152
+ }
153
+ <- fb.orderCh
154
+ }
155
+ fb.done <- struct {}{}
156
+ fb.done <- struct {}{}
157
+ fb.done <- struct {}{}
158
+ fb.done <- struct {}{}
159
+ wg.Wait ()
160
+ }
161
+
162
+ type FizzBuzzStruct struct {
163
+ numberCh chan int
164
+ fizzCh chan struct {}
165
+ buzzCh chan struct {}
166
+ fizzbuzzCh chan struct {}
167
+ orderCh chan struct {}
168
+ done chan struct {}
169
+ }
170
+
171
+ func NewFizzBuzz () *FizzBuzzStruct {
172
+ return &FizzBuzzStruct{
173
+ numberCh: make (chan int ),
174
+ fizzCh: make (chan struct {}),
175
+ buzzCh: make (chan struct {}),
176
+ fizzbuzzCh: make (chan struct {}),
177
+ orderCh: make (chan struct {}),
178
+ done: make (chan struct {}, 4 ),
179
+ }
180
+ }
181
+
182
+ func (fb *FizzBuzzStruct ) fizz () {
183
+ defer wg.Done ()
184
+ for {
185
+ select {
186
+ case <- fb.fizzCh :
187
+ fmt.Print (" fizz" )
188
+ fb.orderCh <- struct {}{}
189
+ case <- fb.done :
190
+ return
191
+ }
192
+ }
193
+ }
194
+
195
+ func (fb *FizzBuzzStruct ) buzz () {
196
+ defer wg.Done ()
197
+ for {
198
+ select {
199
+ case <- fb.buzzCh :
200
+ fmt.Print (" buzz" )
201
+ fb.orderCh <- struct {}{}
202
+ case <- fb.done :
203
+ return
204
+ }
205
+ }
206
+ }
207
+
208
+ func (fb *FizzBuzzStruct ) fizzbuzz () {
209
+ defer wg.Done ()
210
+ for {
211
+ select {
212
+ case <- fb.fizzbuzzCh :
213
+ fmt.Print (" fizzbuzz" )
214
+ fb.orderCh <- struct {}{}
215
+ case <- fb.done :
216
+ return
217
+ }
218
+ }
219
+ }
220
+
221
+ func (fb *FizzBuzzStruct ) number () {
222
+ defer wg.Done ()
223
+ for {
224
+ select {
225
+ case v := <- fb.numberCh :
226
+ fmt.Print (v)
227
+ fb.orderCh <- struct {}{}
228
+ case <- fb.done :
229
+ return
230
+ }
231
+ }
232
+ }
121
233
122
234
```
123
235
0 commit comments