Skip to content

Commit f9ae204

Browse files
authored
Fix race condition due to concurrent use of rand source (#125)
A global rand.Source was being used concurrently, which is not safe.
1 parent fab50f0 commit f9ae204

File tree

1 file changed

+3
-12
lines changed

1 file changed

+3
-12
lines changed

flatfs.go

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -108,14 +108,6 @@ var (
108108
ErrInvalidKey = errors.New("key not supported by flatfs")
109109
)
110110

111-
var (
112-
r *rand.Rand
113-
)
114-
115-
func init() {
116-
r = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
117-
}
118-
119111
// Datastore implements the go-datastore Interface.
120112
// Note this datastore cannot guarantee order of concurrent
121113
// write operations to the same key. See the explanation in
@@ -862,11 +854,10 @@ func folderSize(path string, deadline time.Time) (int64, initAccuracy, error) {
862854
}
863855

864856
// randomize file order
865-
// https://stackoverflow.com/a/42776696
866-
for i := len(files) - 1; i > 0; i-- {
867-
j := r.Intn(i + 1)
857+
r := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
858+
r.Shuffle(len(files), func(i, j int) {
868859
files[i], files[j] = files[j], files[i]
869-
}
860+
})
870861

871862
accuracy := exactA
872863
for {

0 commit comments

Comments
 (0)