Skip to content

Commit

Permalink
- removed mutex operation, removed Toggle function as it is un-implem…
Browse files Browse the repository at this point in the history
…entable using atomic operations on an uint32 value
  • Loading branch information
iulianpascalau committed Dec 22, 2021
1 parent 7a7b23c commit 577add3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 51 deletions.
40 changes: 12 additions & 28 deletions core/atomic/flag.go
Original file line number Diff line number Diff line change
@@ -1,50 +1,34 @@
package atomic

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

// Flag is an atomic flag
type Flag struct {
mut sync.RWMutex
value bool
value uint32
}

// SetReturningPrevious sets flag and returns its previous value
func (flag *Flag) SetReturningPrevious() bool {
flag.mut.Lock()
previousValue := flag.value
flag.value = true
flag.mut.Unlock()

return previousValue
previousValue := atomic.SwapUint32(&flag.value, 1)
return previousValue == 1
}

// Reset resets the flag, putting it in off position
func (flag *Flag) Reset() {
flag.mut.Lock()
flag.value = false
flag.mut.Unlock()
atomic.StoreUint32(&flag.value, 0)
}

// IsSet checks whether flag is set
func (flag *Flag) IsSet() bool {
flag.mut.RLock()
defer flag.mut.RUnlock()

return flag.value
}

// Toggle toggles the flag
func (flag *Flag) Toggle() {
flag.mut.Lock()
flag.value = !flag.value
flag.mut.Unlock()
value := atomic.LoadUint32(&flag.value)
return value == 1
}

// SetValue sets the new value in the flag
func (flag *Flag) SetValue(newValue bool) {
flag.mut.Lock()
flag.value = newValue
flag.mut.Unlock()
if newValue {
_ = flag.SetReturningPrevious()
} else {
flag.Reset()
}
}
23 changes: 0 additions & 23 deletions core/atomic/flag_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package atomic

import (
"github.com/stretchr/testify/assert"
"sync"
"testing"

Expand Down Expand Up @@ -95,25 +94,3 @@ func TestFlag_SetValue(t *testing.T) {
wg.Wait()
require.False(t, flag.IsSet())
}

func TestFlag_Toggle(t *testing.T) {
t.Parallel()

f := Flag{}
f.SetValue(true)

numToggles := 51
wg := sync.WaitGroup{}
wg.Add(numToggles)
for i := 0; i < numToggles; i++ {
go func() {
f.Toggle()

wg.Done()
}()
}

wg.Wait()

assert.False(t, f.IsSet())
}

0 comments on commit 577add3

Please sign in to comment.