Skip to content

Commit

Permalink
Merge pull request #47 from ElrondNetwork/atomic-flag-refactor
Browse files Browse the repository at this point in the history
Refactored the Flag implementation
  • Loading branch information
iulianpascalau authored Dec 27, 2021
2 parents 8446bf7 + 577add3 commit 9733e61
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 20 deletions.
18 changes: 9 additions & 9 deletions core/atomic/flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ type Flag struct {
value uint32
}

// Set sets flag and returns its previous value
func (flag *Flag) Set() bool {
// SetReturningPrevious sets flag and returns its previous value
func (flag *Flag) SetReturningPrevious() bool {
previousValue := atomic.SwapUint32(&flag.value, 1)
return previousValue == 1
}

// Unset sets flag
func (flag *Flag) Unset() {
// Reset resets the flag, putting it in off position
func (flag *Flag) Reset() {
atomic.StoreUint32(&flag.value, 0)
}

Expand All @@ -24,11 +24,11 @@ func (flag *Flag) IsSet() bool {
return value == 1
}

// Toggle toggles the flag
func (flag *Flag) Toggle(set bool) {
if set {
flag.Set()
// SetValue sets the new value in the flag
func (flag *Flag) SetValue(newValue bool) {
if newValue {
_ = flag.SetReturningPrevious()
} else {
flag.Unset()
flag.Reset()
}
}
28 changes: 17 additions & 11 deletions core/atomic/flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
)

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

var flag Flag
var wg sync.WaitGroup

Expand All @@ -16,56 +18,60 @@ func TestFlag_Set(t *testing.T) {
wg.Add(2)

go func() {
flag.Set()
_ = flag.SetReturningPrevious()
wg.Done()
}()

go func() {
flag.Set()
_ = flag.SetReturningPrevious()
wg.Done()
}()

wg.Wait()
require.True(t, flag.IsSet())
}

func TestFlag_Unset(t *testing.T) {
func TestFlag_Reset(t *testing.T) {
t.Parallel()

var flag Flag
var wg sync.WaitGroup

flag.Set()
_ = flag.SetReturningPrevious()
require.True(t, flag.IsSet())

wg.Add(2)

go func() {
flag.Unset()
flag.Reset()
wg.Done()
}()

go func() {
flag.Unset()
flag.Reset()
wg.Done()
}()

wg.Wait()
require.False(t, flag.IsSet())
}

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

var flag Flag
var wg sync.WaitGroup

// First, Toggle(true)
wg.Add(2)

go func() {
flag.Toggle(true)
flag.SetValue(true)
wg.Done()
}()

go func() {
flag.Toggle(true)
flag.SetValue(true)
wg.Done()
}()

Expand All @@ -76,12 +82,12 @@ func TestFlag_Toggle(t *testing.T) {
wg.Add(2)

go func() {
flag.Toggle(false)
flag.SetValue(false)
wg.Done()
}()

go func() {
flag.Toggle(false)
flag.SetValue(false)
wg.Done()
}()

Expand Down

0 comments on commit 9733e61

Please sign in to comment.