default math.rand.source is thread save while rand.new source is not

Default math rand.Source is thread save while rand.New is not

Default pacakge rand uses Source that is thread safe with default seed 1
we can use the pacakge's method to have thread safe random number generation
1
package main
2
​
3
import (
4
"fmt"
5
"math/rand"
6
"time"
7
)
8
​
9
func main() {
10
seed := time.Now().UnixNano()
11
rand.Seed(seed)
12
fmt.Println(rand.Int63())
13
}
Copied!
But the rand.NewSource() offers thread unsafe implementation. One of the reason to choose the unsafe implementation to avoid synchronization, especially when you have only single go routine.
1
package main
2
​
3
import (
4
"fmt"
5
"math/rand"
6
"time"
7
)
8
​
9
func main() {
10
seed := time.Now().UnixNano()
11
r := rand.New(rand.NewSource(seed))
12
fmt.Println(r.Int63())
13
}
Copied!
Last modified 1mo ago
Copy link