Skip to content

Commit c2c9937

Browse files
authored
Remove go1.18 support and update the implementation of the CBool (#23)
1 parent 5105360 commit c2c9937

File tree

4 files changed

+50
-18
lines changed

4 files changed

+50
-18
lines changed

.github/workflows/go.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ jobs:
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:

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module github.com/no-src/log
22

3-
go 1.18
3+
go 1.19

internal/cbool/cbool.go

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,34 @@
11
package cbool
22

3-
import "sync"
3+
import (
4+
"sync/atomic"
5+
)
46

57
// CBool a concurrent safe bool
68
type CBool struct {
7-
v bool
8-
mu sync.RWMutex
9+
v atomic.Bool
910
}
1011

1112
// New create an instance of CBool
1213
func 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
1920
func (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
2625
func (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
3330
func (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

internal/cbool/cbool_test.go

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package cbool
22

3-
import "testing"
3+
import (
4+
"sync"
5+
"testing"
6+
)
47

58
func 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+
}

0 commit comments

Comments
 (0)