Aha, an interesting Go concurrency question

Original link: https://colobu.com/2022/09/01/fizzbuzz-in-go/

Today, a classmate gave me a concurrent question. As the author of “GO Concurrent Programming Practical Course” in geek time, I didn’t answer it for a while. I am ashamed, so I studied the topic in the evening and gave some tips. Implementation options are discussed.

This question seems to have been seen somewhere, and I found it with memory. It turned out to be a concurrent question of Leetcode. This question says:

Write a program that outputs a string representing this number from 1 to n, but:

If the number is divisible by 3, output “fizz”.
If the number is divisible by 5, output “buzz”.
If the number is divisible by both 3 and 5, output “fizzbuzz”.
For example, when n = 15, output: 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz.

Suppose there is such a class:


1
2
3
4
5
6
7

class FizzBuzz {
public FizzBuzz ( int n) { … } // constructor
public void fizz (printFizz) { … } // only output “fizz”
public void buzz (printBuzz) { … } // only output “buzz”
public void fizzbuzz (printFizzBuzz) { … } // only output “fizzbuzz”
public void number (printNumber) { … } // only output the numbers
}

Please implement a multi-threaded version of FizzBuzz with four threads. The same FizzBuzz instance will be used by the following four threads:

Thread A will call fizz() to determine if it is divisible by 3, and if so, output fizz.
Thread B will call buzz() to determine if it is divisible by 5, and if so, output buzz.
Thread C will call fizzbuzz() to determine if it is divisible by both 3 and 5, and if so, output fizzbuzz.
Thread D will call number() to output a number that is neither divisible by 3 nor divisible by 5.

Basically, this is a concurrency problem of task scheduling, which can actually be implemented using the simplest concurrency primitives.

Convert concurrent to serial

I started thinking wrong, I want to implement a manager to schedule four goroutines, but there is actually the simplest rough and fast method, just like the question I gave in the column “Drumming Passing Flowers”, you can Serialize these four goroutines.

Each number is handed over to a goroutine to process, if it is not responsible for processing, then it is handed over to the next goroutine.
The beauty of this question is that these four cases are not intersected, a number can only be processed by one goroutine, and there must be one goroutine to process it, which is easy to handle. During the handover of the four goroutines, there must be one goroutine that will output the content. If it outputs the content, it will increase the number by one and hand it over to the next goroutine to check and process, which starts a new round of numbers. inspection and processing.

When the number processed is greater than the specified number, it passes the number to the next goroutine and returns. This way the next goroutine will return with the same processing. The last four goroutines all return.

We use a WaitGroup to wait for all four goroutines to return, then the program exits.

code show as below:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
twenty one
twenty two
twenty three
twenty four
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155

package main
import (
“fmt”
“sync”
)
type FizzBuzz struct {
n int
chs [] chan int
wg sync.WaitGroup
}
func New(n int ) *FizzBuzz {
chs := make ([] chan int , 4 )
for i := 0 ; i < 4 ; i++ {
chs[i] = make ( chan int , 1 )
}
return &FizzBuzz{
n: n,
chs: chs,
}
}
func (fb *FizzBuzz) start() {
fb.wg.Add (4 )
go fb.fizz()
go fb.buzz()
go fb.fizzbuzz()
go fb.number()
fb.chs [0 ] <- 1
fb.wg.Wait()
}
func (fb *FizzBuzz) fizz() {
defer fb.wg.Done()
next := fb.chs [1 ]
for v := range fb.chs [0 ] {
if v > fb.n {
next <- v
return
}
if v %3 == 0 {
if v %5 == 0 {
next <- v
continue
}
if v == fb.n {
fmt.Print( “fizz.” )
} else {
fmt.Print( “fizz,” )
}
next <- v + 1
continue
}
next <- v
}
}
func (fb *FizzBuzz) buzz() {
defer fb.wg.Done()
next := fb.chs [2 ]
for v := range fb.chs [1 ] {
if v > fb.n {
next <- v
return
}
if v %5 == 0 {
if v %3 == 0 {
next <- v
continue
}
if v == fb.n {
fmt.Print( “buzz.” )
} else {
fmt.Print( ”buzz,” )
}
next <- v + 1
continue
}
next <- v
}
}
func (fb *FizzBuzz) fizzbuzz() {
defer fb.wg.Done()
next := fb.chs [3 ]
for v := range fb.chs [2 ] {
if v > fb.n {
next <- v
return
}
if v %5 == 0 && v %3 == 0 {
if v == fb.n {
fmt.Print( “fizzbuzz.” )
} else {
fmt.Print( “fizzbuzz,” )
}
next <- v + 1
continue
}
next <- v
}
}
func (fb *FizzBuzz) number() {
defer fb.wg.Done()
next := fb.chs [0 ]
for v := range fb.chs [3 ] {
if v > fb.n {
next <- v
return
}
if v %5 != 0 && v %3 != 0 {
if v == fb.n {
fmt.Printf( “%d.” , v)
} else {
fmt.Printf( ” %d,” , v)
}
next <- v + 1
continue
}
next <- v
}
}
func main() {
fb := New (15 )
fb.start()
}

use a channel

The above-mentioned conversion of concurrency into serial operations always makes people feel unsatisfactory, and we prefer to execute them concurrently.

So you can change the idea, four goroutines use the same channel. If a goroutine is very lucky and takes a value from this channel, it will check, but there are two cases:

  • It is exactly the number that it wants to process: it outputs the corresponding text, adds one to the value, and puts it into the channel
  • Not the number to be processed by yourself: put this number back into the channel

For each number, there will always be a goroutine that fetches it and processes it.

When the number taken out is greater than the specified number, put the number back into the channel and return.

code show as below:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
twenty one
twenty two
twenty three
twenty four
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147

package main
import (
“fmt”
“sync”
)
type FizzBuzz struct {
n int
ch chan int
wg sync.WaitGroup
}
func New(n int ) *FizzBuzz {
return &FizzBuzz{
n: n,
ch: make ( chan int , 1 ),
}
}
func (fb *FizzBuzz) start() {
fb.wg.Add (4 )
go fb.fizz()
go fb.buzz()
go fb.fizzbuzz()
go fb.number()
fb.ch <- 1
fb.wg.Wait()
}
func (fb *FizzBuzz) fizz() {
defer fb.wg.Done()
for v := range fb.ch {
if v > fb.n {
fb.ch <- v
return
}
if v %3 == 0 {
if v %5 == 0 {
fb.ch <- v
continue
}
if v == fb.n {
fmt.Print( “fizz.” )
} else {
fmt.Print( “fizz,” )
}
fb.ch <- v + 1
continue
}
fb.ch <- v
}
}
func (fb *FizzBuzz) buzz() {
defer fb.wg.Done()
for v := range fb.ch {
if v > fb.n {
fb.ch <- v
return
}
if v %5 == 0 {
if v %3 == 0 {
fb.ch <- v
continue
}
if v == fb.n {
fmt.Print( “buzz.” )
} else {
fmt.Print( ”buzz,” )
}
fb.ch <- v + 1
continue
}
fb.ch <- v
}
}
func (fb *FizzBuzz) fizzbuzz() {
defer fb.wg.Done()
for v := range fb.ch {
if v > fb.n {
fb.ch <- v
return
}
if v %5 == 0 && v %3 == 0 {
if v == fb.n {
fmt.Print( “fizzbuzz.” )
} else {
fmt.Print( “fizzbuzz,” )
}
fb.ch <- v + 1
continue
}
fb.ch <- v
}
}
func (fb *FizzBuzz) number() {
defer fb.wg.Done()
for v := range fb.ch {
if v > fb.n {
fb.ch <- v
return
}
if v %5 != 0 && v %3 != 0 {
if v == fb.n {
fmt.Printf( “%d.” , v)
} else {
fmt.Printf( ” %d,” , v)
}
fb.ch <- v + 1
continue
}
fb.ch <- v
}
}
func main() {
fb := New (15 )
fb.start()
}

Here is a knowledge point: Will there always be only one goroutine that takes the value out and puts it back, and takes it out and puts it back, and other goroutines have no chance to read the value?

No, according to the implementation of the channel, the waiter still has a first come first served, a goroutine always has the opportunity to get the data to be processed.

use a fence

In fact, what I have always wanted to achieve is to use cyclic barrier . Some students may not be familiar with this concurrency primitive, but for this scenario, using Barrier code is very concise and the logic is very clear.
And the loop fence is more suitable for the scene of this song, because we are going to reuse the fence.

For each number, we set up a fence for every goroutine to check and process, and one of the four goroutines will always process the number. After processing this number, increment the number by one and wait for the next fence release.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
twenty one
twenty two
twenty three
twenty four
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173

package main
import (
“context”
“fmt”
“sync”
“github.com/marusama/cyclicbarrier”
)
// Write a program that prints a string representing this number from 1 to n, requiring:
// If the number is divisible by 3, print “fizz”.
// If the number is divisible by 5, print “buzz”.
// If the number is divisible by both 3 and 5, print “fizzbuzz”.
// For example, when n = 15, output: 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz.
// Suppose there is such a structure:
// type FizzBuzz struct {}
// func (fb *FizzBuzz) fizz() {}
// func (fb *FizzBuzz) buzz() {}
// func (fb *FizzBuzz) fizzbuzz() {}
// func (fb *FizzBuzz) number() {}
// Please implement a multi-coroutine version of FizzBuzz with four threads. The same FizzBuzz object will be used by the following four coroutines:
// Coroutine A will call fizz() to determine if it is divisible by 3, and if so, output fizz.
// Coroutine B will call buzz() to determine if it is divisible by 5, and if so, output buzz.
// Coroutine C will call fizzbuzz() to determine if it is divisible by both 3 and 5, and if so, output fizzbuzz.
// coroutine D will call number() to output a number that is neither divisible by 3 nor divisible by 5.
type FizzBuzz struct {
n int
v int
barrier cyclicbarrier.CyclicBarrier
wg sync.WaitGroup
}
func New(n int ) *FizzBuzz {
return &FizzBuzz{
n: n,
barrier: cyclicbarrier.New (4 ),
}
}
func (fb *FizzBuzz) start() {
fb.wg.Add (4 )
go fb.fizz()
go fb.buzz()
go fb.fizzbuzz()
go fb.number()
fb.v++
fb.wg.Wait()
}
func (fb *FizzBuzz) fizz() {
defer fb.wg.Done()
ctx := context.Background()
for {
fb.barrier.Await(ctx)
v := fb.v
if v > fb.n {
return
}
if v %3 == 0 {
if v %5 == 0 {
continue
}
if v == fb.n {
fmt.Print( “fizz.” )
} else {
fmt.Print( “fizz,” )
}
fb.v++
}
}
}
func (fb *FizzBuzz) buzz() {
defer fb.wg.Done()
ctx := context.Background()
for {
fb.barrier.Await(ctx)
v := fb.v
if v > fb.n {
return
}
if v %5 == 0 {
if v %3 == 0 {
continue
}
if v == fb.n {
fmt.Print( “buzz.” )
} else {
fmt.Print( ”buzz,” )
}
fb.v++
}
}
}
func (fb *FizzBuzz) fizzbuzz() {
defer fb.wg.Done()
ctx := context.Background()
for {
fb.barrier.Await(ctx)
v := fb.v
if v > fb.n {
return
}
if v %5 == 0 && v %3 == 0 {
if v == fb.n {
fmt.Print( “fizzbuzz.” )
} else {
fmt.Print( “fizzbuzz,” )
}
fb.v++
continue
}
}
}
func (fb *FizzBuzz) number() {
defer fb.wg.Done()
ctx := context.Background()
for {
fb.barrier.Await(ctx)
v := fb.v
if v > fb.n {
return
}
if v %5 != 0 && v %3 != 0 {
if v == fb.n {
fmt.Printf( “%d.” , v)
} else {
fmt.Printf( ” %d,” , v)
}
fb.v++
continue
}
}
}
func main() {
fb := New (15 )
fb.start()
}

Use other concurrency primitives

I also thought of concurrency primitives like sync.Cond , Semaphore , WaitGroup , etc. Simple After the evaluation, I feel that it is not appropriate to use these concurrency primitives for task scheduling.

  • sync.Cond : It seems to be possible, but in actual use, it is not easy to make these four goroutines “self-consistent” to implement Wait/Broadcast. It seems okay to use an additional goroutine as Manager
  • Semaphore : Each goroutine acquires a semaphore. After the corresponding goroutine is processed, the number is increased by one, and then the semaphore is released. But there is a possibility of starvation, always a goroutine requests the semaphore to release the semaphore
  • WaitGroup : The biggest difficulty of WaitGroup in this scenario is to reuse it, and reuse of WaitGroup can easily lead to panic

So these three concurrency primitives I tried and gave up. I personally prefer the implementation of Barrier, although it has the disadvantage of “shocking herd”, but it is not a big problem for this problem.

If you have any ideas and implementations, please leave a message in the comment area of ​​the original link.

This article is reprinted from: https://colobu.com/2022/09/01/fizzbuzz-in-go/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment