The golang docs says that
Seed, unlike the Rand.Seed method, is safe for concurrent use.
The rand.Seed
is actually from math/rand
package, but what is Seed? If Seed
is another function then it's not present in math/rand
so it's unclear from where that function comes from?
update: I'm exploring the demo program where in main
we execute
rand.Seed(time.Now().UnixNano())
go process(...)
go process(...)
where the process
is determined like
func process(...) {
time.Sleep(time.Duration(rand.Intn(30)) * time.Second)
...
}
We are using the same seed in two different threads, so is such using of rand.Seed
considered to be a thread non-safe?
There is a rand.Seed()
function, and there is a Rand.Seed()
method. Your quote originates from the documentation of the Rand.Seed()
method.
Global functions of the math/rand
package operate on a global rand.Rand
instance. If you check the source code of rand.Seed()
:
func Seed(seed int64) { globalRand.Seed(seed) }
The global functions are safe for concurrent use, so all other packages can use it (in a shared manner). The global rand.Rand
instance is provided for convenience, you can use it "out-of-the box" without any preparation (except the need to properly seed it) and without any synchronization.
Instances of rand.Rand
are not safe for concurrent use, each goroutine that needs a rand.Rand
for deterministic random sequences should create one, and seed it appropriately. Or if a rand.Rand
is to be shared between multiple goroutines, explicit synchronization is required.
Pros of using the global rand.Rand
(via the global functions) are: (1) ease of use (it's implicitly shared with everyone) and (2) no synchronization is needed.
Pros of creating and using a custom rand.Rand
instance: (1) it's faster (it's not synchronized implicitly) and (2) you are in control of who has access to it, so you can use it to repeat pseudo-random sequences (you can't do that with the global instance as "anyone" may use it concurrently with you).
Edit:
We are using the same seed in two different threads, so is such using of
rand.Seed
considered to be a thread non-safe?
You only call rand.Seed
once, so actually it doesn't even matter if it's thread safe or not, it is not called concurrently. If rand.Seed()
would be called from multiple goroutines concurrently, only then would it matter whether it's safe for concurrent use. And as stated earlier in my answer: "The global functions are safe for concurrent use..."
What you do call from multiple goroutines concurrently is rand.Intn()
, but again, it's safe to do that.