Skip to content

Commit

Permalink
Remove go1.18 support and update the implementation of the CBool (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
mstmdev authored Aug 19, 2023
1 parent 5105360 commit c2c9937
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 18 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
build:
strategy:
matrix:
go: [ '1.18','1.19','1.20','1.21' ]
go: [ '1.19','1.20','1.21' ]
os: [ 'ubuntu-latest', 'windows-latest', 'macos-latest' ]
runs-on: ${{ matrix.os }}
steps:
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/no-src/log

go 1.18
go 1.19
25 changes: 10 additions & 15 deletions internal/cbool/cbool.go
Original file line number Diff line number Diff line change
@@ -1,39 +1,34 @@
package cbool

import "sync"
import (
"sync/atomic"
)

// CBool a concurrent safe bool
type CBool struct {
v bool
mu sync.RWMutex
v atomic.Bool
}

// New create an instance of CBool
func New(v bool) *CBool {
return &CBool{
v: v,
}
cb := &CBool{}
cb.v.Store(v)
return cb
}

// Get return the bool value
func (cb *CBool) Get() bool {
cb.mu.RLock()
defer cb.mu.RUnlock()
return cb.v
return cb.v.Load()
}

// Set to set the bool value
func (cb *CBool) Set(v bool) {
cb.mu.Lock()
defer cb.mu.Unlock()
cb.v = v
cb.v.Store(v)
}

// SetC to set the bool value and return a closed channel
func (cb *CBool) SetC(v bool) <-chan struct{} {
cb.mu.Lock()
defer cb.mu.Unlock()
cb.v = v
cb.Set(v)
c := make(chan struct{})
close(c)
return c
Expand Down
39 changes: 38 additions & 1 deletion internal/cbool/cbool_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package cbool

import "testing"
import (
"sync"
"testing"
)

func TestCBool(t *testing.T) {
expect := true
Expand Down Expand Up @@ -28,3 +31,37 @@ func TestCBool(t *testing.T) {
t.Errorf("test CBoll SetC value failed, channel should be closed")
}
}

func TestCBool_Concurrent(t *testing.T) {
cb := New(false)
wg := sync.WaitGroup{}
count := 10
wg.Add(count * 3)
for i := 0; i < count; i++ {
go func() {
cb.Get()
wg.Done()
}()

go func() {
cb.Set(true)
wg.Done()
}()

go func() {
<-cb.SetC(true)
wg.Done()
}()
}
wg.Wait()
}

func BenchmarkCBool(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
cb := New(false)
for i := 0; i < b.N; i++ {
cb.Set(true)
cb.Get()
}
}

0 comments on commit c2c9937

Please sign in to comment.