File tree Expand file tree Collapse file tree 1 file changed +22
-4
lines changed
topics/go/concurrency/patterns/advanced Expand file tree Collapse file tree 1 file changed +22
-4
lines changed Original file line number Diff line number Diff line change @@ -9,18 +9,22 @@ import (
9
9
"log"
10
10
"os"
11
11
"os/signal"
12
- "sync/atomic "
12
+ "sync"
13
13
"time"
14
14
)
15
15
16
16
// device allows us to mock a device we write logs to.
17
17
type device struct {
18
- problem int32
18
+ mu sync.RWMutex
19
+ problem bool
19
20
}
20
21
21
22
// Write implements the io.Writer interface.
22
23
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
+ }
24
28
25
29
// Simulate disk problems.
26
30
time .Sleep (time .Second )
@@ -30,6 +34,20 @@ func (d *device) Write(p []byte) (n int, err error) {
30
34
return len (p ), nil
31
35
}
32
36
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
+
33
51
func main () {
34
52
35
53
// Number of goroutines that will be writing logs.
@@ -59,6 +77,6 @@ func main() {
59
77
60
78
for {
61
79
<- sigChan
62
- atomic . StoreInt32 ( & d . problem , 1 - atomic . LoadInt32 ( & d . problem ) )
80
+ d . flipProblem ( )
63
81
}
64
82
}
You can’t perform that action at this time.
0 commit comments