Skip to content

Commit 0088d51

Browse files
committed
small examples + readme adjustments
1 parent ec96b72 commit 0088d51

File tree

4 files changed

+43
-6
lines changed

4 files changed

+43
-6
lines changed

atomics/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,7 @@ go tool objdump -s main.main exec
281281

282282
- [Race Example](https://github.com/golang-basics/concurrency/blob/master/atomics/race/main.go)
283283
- [Basic Counter](https://github.com/golang-basics/concurrency/blob/master/atomics/basic-counter/main.go)
284+
- [Race Fixed Example](https://github.com/golang-basics/concurrency/blob/master/atomics/race-fixed/main.go)
284285
- [atomic.Value - Reader/Writer Example](https://github.com/golang-basics/concurrency/blob/master/atomics/value/reader-writer/main.go)
285286
- [atomic.Value - Calculator Example](https://github.com/golang-basics/concurrency/blob/master/atomics/value/calculator/main.go)
286287
- [atomic.Value - panic](https://github.com/golang-basics/concurrency/blob/master/atomics/value/panic/main.go)

atomics/basic-counter/main.go

+5-5
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,19 @@ func main() {
1515

1616
wg.Add(1)
1717
go func() {
18+
defer wg.Done()
1819
time.Sleep(10 * time.Millisecond)
19-
fmt.Println(atomic.LoadInt64(&count))
20-
wg.Done()
20+
fmt.Println("count in go routine", atomic.LoadInt64(&count))
2121
}()
2222

23+
wg.Add(50)
2324
for i := 0; i < 50; i++ {
24-
wg.Add(1)
2525
go func() {
26+
defer wg.Done()
2627
time.Sleep(10 * time.Millisecond)
2728
atomic.AddInt64(&count, 1)
28-
wg.Done()
2929
}()
3030
}
3131
wg.Wait()
32-
fmt.Println(count)
32+
fmt.Println("count in main", count)
3333
}

atomics/race-fixed/main.go

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"sync"
6+
"sync/atomic"
7+
)
8+
9+
func main() {
10+
var count int32
11+
var wg sync.WaitGroup
12+
wg.Add(5)
13+
go func() {
14+
defer wg.Done()
15+
atomic.StoreInt32(&count, 10)
16+
}()
17+
go func() {
18+
defer wg.Done()
19+
atomic.StoreInt32(&count, -15)
20+
}()
21+
go func() {
22+
defer wg.Done()
23+
atomic.StoreInt32(&count, 1)
24+
}()
25+
go func() {
26+
defer wg.Done()
27+
atomic.StoreInt32(&count, 0)
28+
}()
29+
go func() {
30+
defer wg.Done()
31+
atomic.StoreInt32(&count, 100)
32+
}()
33+
wg.Wait()
34+
35+
fmt.Println("count", count)
36+
}

atomics/value/reader-writer/main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,14 @@ func main() {
3535
wg.Add(5)
3636
for i := 0; i < 5; i++ {
3737
go func() {
38+
defer wg.Done()
3839
// we're gonna get a panic this way
3940
// cfg := v.Load().(Config)
4041
cfg, ok := v.Load().(Config)
4142
if !ok {
4243
log.Fatalf("received different type: %T", cfg)
4344
}
4445
fmt.Println("cfg", cfg)
45-
wg.Done()
4646
}()
4747
}
4848
wg.Wait()

0 commit comments

Comments
 (0)