Skip to content

Commit dc4170e

Browse files
committed
you're doing great
1 parent abbe53a commit dc4170e

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math/rand"
6+
"sync"
7+
"time"
8+
)
9+
10+
var wg sync.WaitGroup
11+
12+
type SafeCounter struct {
13+
c int
14+
sync.Mutex
15+
}
16+
17+
func (c *SafeCounter) Add() {
18+
c.Lock()
19+
defer c.Unlock()
20+
c.c++
21+
}
22+
23+
var counter *SafeCounter = &SafeCounter{}
24+
25+
func main() {
26+
27+
fmt.Println(&counter.c)
28+
29+
wg.Add(2)
30+
go incrementor("Foo:")
31+
go incrementor("Bar:")
32+
wg.Wait()
33+
fmt.Println("Final Counter:", counter.c)
34+
}
35+
36+
func incrementor(s string) {
37+
rand.Seed(time.Now().UnixNano())
38+
for i := 0; i < 20; i++ {
39+
x := counter
40+
fmt.Println("1----",counter)
41+
fmt.Println("2----",x)
42+
x.Add()
43+
counter = x
44+
time.Sleep(time.Duration(rand.Intn(3)) * time.Millisecond)
45+
fmt.Println(s, i, "Counter:", counter.c)
46+
}
47+
wg.Done()
48+
}
49+
50+
// go run -race main.go
51+
// vs
52+
// go run main.go
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math/rand"
6+
"sync"
7+
"time"
8+
)
9+
10+
var wg sync.WaitGroup
11+
12+
type SafeCounter struct {
13+
c int
14+
m sync.Mutex
15+
}
16+
17+
func (sc *SafeCounter) Add() {
18+
sc.m.Lock()
19+
defer sc.m.Unlock()
20+
sc.c++
21+
}
22+
23+
var counter *SafeCounter = &SafeCounter{}
24+
25+
func main() {
26+
27+
fmt.Println(&counter.c)
28+
29+
wg.Add(2)
30+
go incrementor("Foo:")
31+
go incrementor("Bar:")
32+
wg.Wait()
33+
fmt.Println("Final Counter:", counter.c)
34+
}
35+
36+
func incrementor(s string) {
37+
rand.Seed(time.Now().UnixNano())
38+
for i := 0; i < 20; i++ {
39+
counter.Add()
40+
time.Sleep(time.Duration(rand.Intn(3)) * time.Millisecond)
41+
//fmt.Println(s, i, "Counter:", counter.c) // causes a race; no lock here; multiple goroutines accessing to READ the value
42+
}
43+
wg.Done()
44+
}
45+
46+
// go run -race main.go
47+
// vs
48+
// go run main.go

0 commit comments

Comments
 (0)