Skip to content

Commit e586b1e

Browse files
fixing safe flip code
1 parent 1051182 commit e586b1e

File tree

1 file changed

+22
-4
lines changed
  • topics/go/concurrency/patterns/advanced

1 file changed

+22
-4
lines changed

topics/go/concurrency/patterns/advanced/main.go

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,22 @@ import (
99
"log"
1010
"os"
1111
"os/signal"
12-
"sync/atomic"
12+
"sync"
1313
"time"
1414
)
1515

1616
// device allows us to mock a device we write logs to.
1717
type device struct {
18-
problem int32
18+
mu sync.RWMutex
19+
problem bool
1920
}
2021

2122
// Write implements the io.Writer interface.
2223
func (d *device) Write(p []byte) (n int, err error) {
23-
for atomic.LoadInt32(&d.problem) == 1 {
24+
for {
25+
if !d.isProblem() {
26+
break
27+
}
2428

2529
// Simulate disk problems.
2630
time.Sleep(time.Second)
@@ -30,6 +34,20 @@ func (d *device) Write(p []byte) (n int, err error) {
3034
return len(p), nil
3135
}
3236

37+
// isProblem checks in a safe way if there is a problem.
38+
func (d *device) isProblem() bool {
39+
d.mu.RLock()
40+
defer d.mu.RUnlock()
41+
return d.problem
42+
}
43+
44+
// flipProblem reverses the problem flag to the opposite value.
45+
func (d *device) flipProblem() {
46+
d.mu.Lock()
47+
defer d.mu.Unlock()
48+
d.problem = !d.problem
49+
}
50+
3351
func main() {
3452

3553
// Number of goroutines that will be writing logs.
@@ -59,6 +77,6 @@ func main() {
5977

6078
for {
6179
<-sigChan
62-
atomic.StoreInt32(&d.problem, 1-atomic.LoadInt32(&d.problem))
80+
d.flipProblem()
6381
}
6482
}

0 commit comments

Comments
 (0)