Go's random package has a function called NewSource that helps create a random number generator with a custom seed.
The comment on the source code mentions https://github.com/golang/go/blob/master/src/math/rand/rand.go#L41
// Unlike the default Source used by top-level functions, this source is not
// safe for concurrent use by multiple goroutines.
What I don't understand is
- Is the
NewSourcealone not safe for concurrent use ? OR - Is the random number generator that is constructed out of this new source not safe for concurrent use as well ?
Example program
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func main() {
// NewSource NOT safe for concurrent use
rng := rand.New(rand.NewSource(time.Now().Unix()))
//is the random number generator rng safe for concurrent use
//since the NewSource is used only during the instantiation
//or is the seed being internally modified everytime rng generates a random number
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fmt.Printf("random number is: %f \n", rng.Float64())
}()
}
wg.Wait()
}