英文:
Is Golang crypto/rand thread safe?
问题
math/rand.Rand的源代码中指出,Read
方法在共享源时不是线程安全的。那么crypto/rand呢?源代码中指出它使用getrandom(2)
或/dev/urandom
,但不清楚在并发调用时会发生什么。
更新:评论已经帮助澄清了math/rand.Read()
和math/rand.Rand.Read()
之间的区别。
为了实现线程安全:
- 当并发调用
Read
时,会发生恐慌吗? - 当并发调用时,它会保持随机序列吗?还是可能给并发调用者提供重复的值?
英文:
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:
- Will it panic when
Read
is called concurrently? - Will it keep the random sequence when called concurrently? Or can duplicates be given to concurrent callers?
答案1
得分: 3
-
crypto/rand
中的rand.Reader
必须支持并发访问,因为它被定义为“一个全局的、共享的密码安全随机数生成器的实例”。在不同的包之间无法同步其使用。 -
crypto/rand
中的rand.Read
是安全的,因为rand.Reader
是安全的,并且它不会访问任何其他共享状态。
英文:
rand.Reader
fromcrypto/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.rand.Read
fromcrypto/rand
is safe because therand.Reader
is safe, and it does not access any other shared state.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论