Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

command/expand: fix data race for concurrent writes #330

Merged
merged 3 commits into from
Aug 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions atomic/bool.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package atomic

import "sync/atomic"

// Bool is an atomic Boolean.
type Bool int32

// Set sets the Boolean to value.
func (b *Bool) Set(value bool) {
var i int32 = 0
if value {
i = 1
}

atomic.StoreInt32((*int32)(b), int32(i))
}

// Get gets the Boolean value.
func (b *Bool) Get() bool {
return atomic.LoadInt32((*int32)(b)) != 0
}
32 changes: 32 additions & 0 deletions atomic/bool_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package atomic

import (
"sync"
"testing"
)

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

var wg sync.WaitGroup
var atomicBool Bool
repeat := 10000

wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < repeat; i++ {
atomicBool.Set(true)
}
}()

wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < repeat; i++ {
_ = atomicBool.Get()
}
}()

wg.Wait()
}
7 changes: 4 additions & 3 deletions command/expand.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"sync"

"github.com/peak/s5cmd/atomic"
"github.com/peak/s5cmd/storage"
"github.com/peak/s5cmd/storage/url"
)
Expand Down Expand Up @@ -58,7 +59,7 @@ func expandSources(
defer close(ch)

var wg sync.WaitGroup
var objFound bool
var objFound atomic.Bool

for _, origSrc := range srcurls {
wg.Add(1)
Expand All @@ -76,13 +77,13 @@ func expandSources(
continue
}
ch <- object
objFound = true
objFound.Set(true)
}
}(origSrc)
}

wg.Wait()
if !objFound {
if !objFound.Get() {
ch <- &storage.Object{Err: storage.ErrNoObjectFound}
}
}()
Expand Down