File tree Expand file tree Collapse file tree 4 files changed +50
-18
lines changed Expand file tree Collapse file tree 4 files changed +50
-18
lines changed Original file line number Diff line number Diff line change 1111 build :
1212 strategy :
1313 matrix :
14- go : [ '1.18','1. 19','1.20','1.21' ]
14+ go : [ '1.19','1.20','1.21' ]
1515 os : [ 'ubuntu-latest', 'windows-latest', 'macos-latest' ]
1616 runs-on : ${{ matrix.os }}
1717 steps :
Original file line number Diff line number Diff line change 11module github.com/no-src/log
22
3- go 1.18
3+ go 1.19
Original file line number Diff line number Diff line change 11package cbool
22
3- import "sync"
3+ import (
4+ "sync/atomic"
5+ )
46
57// CBool a concurrent safe bool
68type CBool struct {
7- v bool
8- mu sync.RWMutex
9+ v atomic.Bool
910}
1011
1112// New create an instance of CBool
1213func New (v bool ) * CBool {
13- return & CBool {
14- v : v ,
15- }
14+ cb := & CBool {}
15+ cb . v . Store ( v )
16+ return cb
1617}
1718
1819// Get return the bool value
1920func (cb * CBool ) Get () bool {
20- cb .mu .RLock ()
21- defer cb .mu .RUnlock ()
22- return cb .v
21+ return cb .v .Load ()
2322}
2423
2524// Set to set the bool value
2625func (cb * CBool ) Set (v bool ) {
27- cb .mu .Lock ()
28- defer cb .mu .Unlock ()
29- cb .v = v
26+ cb .v .Store (v )
3027}
3128
3229// SetC to set the bool value and return a closed channel
3330func (cb * CBool ) SetC (v bool ) <- chan struct {} {
34- cb .mu .Lock ()
35- defer cb .mu .Unlock ()
36- cb .v = v
31+ cb .Set (v )
3732 c := make (chan struct {})
3833 close (c )
3934 return c
Original file line number Diff line number Diff line change 11package cbool
22
3- import "testing"
3+ import (
4+ "sync"
5+ "testing"
6+ )
47
58func TestCBool (t * testing.T ) {
69 expect := true
@@ -28,3 +31,37 @@ func TestCBool(t *testing.T) {
2831 t .Errorf ("test CBoll SetC value failed, channel should be closed" )
2932 }
3033}
34+
35+ func TestCBool_Concurrent (t * testing.T ) {
36+ cb := New (false )
37+ wg := sync.WaitGroup {}
38+ count := 10
39+ wg .Add (count * 3 )
40+ for i := 0 ; i < count ; i ++ {
41+ go func () {
42+ cb .Get ()
43+ wg .Done ()
44+ }()
45+
46+ go func () {
47+ cb .Set (true )
48+ wg .Done ()
49+ }()
50+
51+ go func () {
52+ <- cb .SetC (true )
53+ wg .Done ()
54+ }()
55+ }
56+ wg .Wait ()
57+ }
58+
59+ func BenchmarkCBool (b * testing.B ) {
60+ b .ReportAllocs ()
61+ b .ResetTimer ()
62+ cb := New (false )
63+ for i := 0 ; i < b .N ; i ++ {
64+ cb .Set (true )
65+ cb .Get ()
66+ }
67+ }
You can’t perform that action at this time.
0 commit comments