-
Notifications
You must be signed in to change notification settings - Fork 0
/
atomic_types.go
62 lines (50 loc) · 1.12 KB
/
atomic_types.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
package syncs
import (
"sync"
"sync/atomic"
"github.com/devlights/gomy/output"
)
// AtomicTypes -- Go 1.19 から追加された sync/atomic パッケージ内の型についてのサンプルです。
//
// Go 1.18 までの atomic.AddXXXX() を使ったサンプルは atomic_add.go を参照。
//
// # REFERENCES
// - https://dev.to/emreodabas/quick-guide-go-119-features-1j40
// - https://go.dev/doc/go1.19#atomic_types
func AtomicTypes() error {
var (
wg sync.WaitGroup
x atomic.Int32 // atomic.Int32 のゼロ値は0
fn = func(minus bool) {
defer wg.Done()
for i := 0; i < 50000; i++ {
if minus {
x.Add(-1)
} else {
x.Add(1)
}
}
}
)
for i := 0; i < 5; i++ {
wg.Add(2)
go fn(true)
go fn(false)
wg.Wait()
output.Stdoutl("[x]", x.Load())
}
return nil
/*
$ task
task: [build] go build .
task: [run] ./try-golang -onetime
ENTER EXAMPLE NAME: syncs_atomic_types
[Name] "syncs_atomic_types"
[x] 0
[x] 0
[x] 0
[x] 0
[x] 0
[Elapsed] 4.89769ms
*/
}