Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Golang crypto/rand thread safe?

The source of math/rand.Rand states Read is not thread safe (when sharing a source). What about crypto/rand? The source states it uses getrandom(2) or /dev/urandom, but it is unclear what happens with concurrent calls.

Update: comments have helped clarify the distinction

crypto/rand.Reader.Read(b []byte)
crypto/rand.Read(b []byte)

To be a thread safe:

  1. Will it panic when Read is called concurrently?
  2. Will it keep the random sequence when called concurrently? Or can duplicates be given to concurrent callers?
like image 472
Josh Hibschman Avatar asked Oct 19 '25 00:10

Josh Hibschman


1 Answers

  1. rand.Reader from crypto/rand must be safe for concurrent access, because it is defined as "a global, shared instance of a cryptographically secure random number generator". There would be no way to synchronize its use between packages.
  2. rand.Read from crypto/rand is safe because the rand.Reader is safe, and it does not access any other shared state.
like image 76
JimB Avatar answered Oct 21 '25 22:10

JimB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!