> For the complete documentation index, see [llms.txt](https://til.yulrizka.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://til.yulrizka.com/go/default-math.rand.source-is-thread-save-while-rand.new-source-is-not.md).

# 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

```go
package main

import (
  "fmt"
  "math/rand"
  "time"
)

func main() {
  seed := time.Now().UnixNano()
  rand.Seed(seed)
  fmt.Println(rand.Int63())
}
```

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.

```go
package main

import (
  "fmt"
  "math/rand"
  "time"
)

func main() {
  seed := time.Now().UnixNano()
  r := rand.New(rand.NewSource(seed))
  fmt.Println(r.Int63())
}
```
