Golang的crypto/rand包是线程安全的吗?

huangapple go评论93阅读模式
英文:

Is Golang crypto/rand thread safe?

问题

math/rand.Rand的源代码中指出,Read方法在共享源时不是线程安全的。那么crypto/rand呢?源代码中指出它使用getrandom(2)/dev/urandom,但不清楚在并发调用时会发生什么。

更新:评论已经帮助澄清了math/rand.Read()math/rand.Rand.Read()之间的区别。

为了实现线程安全:

  1. 当并发调用Read时,会发生恐慌吗?
  2. 当并发调用时,它会保持随机序列吗?还是可能给并发调用者提供重复的值?
英文:

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 difference between math/rand.Read() and math/rand.Rand.Read()

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?

答案1

得分: 3

  1. crypto/rand 中的 rand.Reader 必须支持并发访问,因为它被定义为“一个全局的、共享的密码安全随机数生成器的实例”。在不同的包之间无法同步其使用。

  2. crypto/rand 中的 rand.Read 是安全的,因为 rand.Reader 是安全的,并且它不会访问任何其他共享状态。

英文:
  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.

huangapple
  • 本文由 发表于 2023年3月9日 21:38:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定