forked from microsoft/docker
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use goroutine-safe version of rand.Source
Signed-off-by: Alexander Morozov <lk4d4@docker.com>
- Loading branch information
Showing
4 changed files
with
64 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package random | ||
|
||
import ( | ||
"math/rand" | ||
"sync" | ||
"time" | ||
) | ||
|
||
// copypaste from standard math/rand | ||
type lockedSource struct { | ||
lk sync.Mutex | ||
src rand.Source | ||
} | ||
|
||
func (r *lockedSource) Int63() (n int64) { | ||
r.lk.Lock() | ||
n = r.src.Int63() | ||
r.lk.Unlock() | ||
return | ||
} | ||
|
||
func (r *lockedSource) Seed(seed int64) { | ||
r.lk.Lock() | ||
r.src.Seed(seed) | ||
r.lk.Unlock() | ||
} | ||
|
||
// NewSource returns math/rand.Source safe for concurrent use and initialized | ||
// with current unix-nano timestamp | ||
func NewSource() rand.Source { | ||
return &lockedSource{ | ||
src: rand.NewSource(time.Now().UnixNano()), | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package random | ||
|
||
import ( | ||
"math/rand" | ||
"sync" | ||
"testing" | ||
) | ||
|
||
// for go test -v -race | ||
func TestConcurrency(t *testing.T) { | ||
rnd := rand.New(NewSource()) | ||
var wg sync.WaitGroup | ||
|
||
for i := 0; i < 10; i++ { | ||
wg.Add(1) | ||
go func() { | ||
rnd.Int63() | ||
wg.Done() | ||
}() | ||
} | ||
wg.Wait() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters